+ 1

What's wrong in the code below ? Help please.

""" Inverting dictionaries. Take a dictionary as input amd return one as output, but the values are now keys and vice versa. """ my_dict = {"john" : 23, "mike" : 24, "argus" : 27} inv_dict = {} for k, v in my_dict.items () : inv_dict [v] = inv_dict[k] print (inv_dict)

2nd Jun 2018, 4:37 AM
Masquerade
Masquerade - avatar
6 Réponses
+ 10
my_dict = {"john" : 23, "mike" : 24, "argus" : 27} inv_dict = {} for k, v in my_dict.items () : inv_dict [v] = k print (inv_dict)
2nd Jun 2018, 4:41 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Yep. The proper syntax to appending items to a dictionary is: dictionary[key] = value. In your code, the line became: dictionary[key] = dictionary [value] which doesn't really work. I guess it was just a typo on your side. Masquerade
2nd Jun 2018, 4:55 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
My guess is that in the for loop, each value of 'k' is a dictionary item so you just need to refer to 'k' as per Hatsy Rei's solution.
2nd Jun 2018, 4:52 AM
Duncan
Duncan - avatar
+ 3
Aah! It wasn't a typo, I have to admit. But I get my mistake now. Thanks a lot Duncan and Hatsy Rei .
2nd Jun 2018, 4:59 AM
Masquerade
Masquerade - avatar
+ 2
oh wow! you are such a life saver, Hatsy ^_^.
2nd Jun 2018, 4:47 AM
Masquerade
Masquerade - avatar
+ 2
Hatsy Rei , can you just do me one more favour and explain what is going wrong in my code. I still don't understand. Sorry.
2nd Jun 2018, 4:48 AM
Masquerade
Masquerade - avatar