+ 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)
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)
+ 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
+ 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.
+ 2
oh wow! you are such a life saver, Hatsy ^_^.
+ 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.