0
votes

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.

1
There doesn't exist a key called 'month', but the value of your key is stored in the month variable. So you should do months_dict[month] to get the key value from the dictionary. There are no single quotes required - Rajarishi Devarajan
That is because the key value is case-sensitive. You are looking for "oct" when the key value is actually "Oct" (Notice the capitalization) - Rajarishi Devarajan

1 Answers

1
votes

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]