John Bear
John Bear

Reputation: 19

How to access the key values in python dictionary with variables?

I have a dict whose keys are numbers. It looks like this:

{'1': 3, '2': 7, '3', 14}

I need to access the value of each key with a variable, but get stuck because of the quotation marks of keys. How can I do that?

Upvotes: 1

Views: 13715

Answers (1)

ilent2
ilent2

Reputation: 5241

You can cast your number to a string,

my_dict = {'1': 3, '2': 7, '3': 14}

number = 2
print(my_dict[str(number)])

Upvotes: 2

Related Questions