Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass an integer as a key in python?

I have written the following code, that works fine when I pass a character or a string as a key.

def myfunc(**num):
    for i in num:
        print(i, num[i])

myfunc(a="One", b="Two")

However, when I try to pass integers instead of a or b, for example:

myfunc(1="One", 2="Two")

I get the following message:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Is there anything I could do about this?

>Solution :

This is not possible, as all keyword arguments are syntactically required to be strings. The error message your example gets is cryptic, but you can easily demonstrate this by passing a dictionary with integer keys as the keyword arguments:

def myfunc(**num):
    for i in num:
        print(i, num[i])


myfunc(**{1: 'one', 2: 'two'})
# TypeError: keywords must be strings

If you must use integer keys, just pass a dictionary as an argument instead and avoid all the problems:

def myfunc(num):
    for i in num:
        print(i, num[i])


myfunc({1: 'one', 2: 'two'})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading