How to pass an integer as a key in python?
Question:
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:
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
Is there anything I could do about this?
Answers:
This is not possible, as all keyword arguments are required to be strings. More technically as Brian pointed out, keyword arguments are syntactically required to be identifiers by definition.
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'})
def print_value(my_dict, key):
print(my_dict[key])
# Define a dictionary
my_dict = {1: 'one', 2: 'two', 3: 'three'}
# Pass an integer key to the function
print_value(my_dict, 2) # Output: two
is this what you are after?
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:
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
Is there anything I could do about this?
This is not possible, as all keyword arguments are required to be strings. More technically as Brian pointed out, keyword arguments are syntactically required to be identifiers by definition.
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'})
def print_value(my_dict, key):
print(my_dict[key])
# Define a dictionary
my_dict = {1: 'one', 2: 'two', 3: 'three'}
# Pass an integer key to the function
print_value(my_dict, 2) # Output: two
is this what you are after?