user3012807
user3012807

Reputation: 1

how to use a dynamic variable as a key in retrieving table value in python?

I am using below python to retrieve the value of month using dictionary, end up unable to use the variable as a key element in using as a key to retrieve the element of table. I would like to know how to use a dynamic variable as a key in accessing the table element.

months_dic = { 'Jan' : 1, 'Feb' : 2 , 'Mar' : 3, 'Apr' : 4, 'May' : 5, 'Jun' : 6, 'Jul' : 7, 'Aug' : 8, 'Sep' : 9, 'Oct' : 10, 'Nov' : 11, 'Dec' : 12 } month = "oct" print (months_dic['month'])

is giving below error KeyError: 'monthi'

I am expected the print value should be 10.

Upvotes: 0

Views: 53

Answers (1)

Rajarishi Devarajan
Rajarishi Devarajan

Reputation: 581

The value of your key is stored in the variable, and to use the value of the variable, you should not use quotes.

months_dict[month]

Upvotes: 1

Related Questions