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?

Asked By: Giorgos

||

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'})
Answered By: Michael M.
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?

Answered By: BGSniper-xll
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.