0
Pls how do I reverse a dictionary?
For example: _dict = { solo:4, learn:2, solearn: 5, Elijah:3, python:21}. I'm trying to sort this in a way I'll get new_dict = {21:python, 5:solearn, 4:solo, 3:Elijah, 2:learn} So I tried to interchanged the dictionary in two ways but both failed 1. new_dict = dic(zip(_dict.values(), _dict.keys())). 2. new_dict = {} for key, value in _dict.items(): new_dict[value] = item. I was hoping to sort it later but both of the algorithms failed
8 Answers
+ 4
Elijah Nwalozie
There is lots of ways to swap Key Value of dictionary.
https://code.sololearn.com/cyW0S7hPc9eV/?ref=app
+ 4
You can do it this way!
a=sorted(_dict.items(),key=lambda x:x[1],reverse=True)
new_dict={i[1]:i[0] for i in a})
+ 2
Calvin Thomas I'll try this too thanks
+ 1
You can also use dictionary comprehension
https://code.sololearn.com/cDkQNzkcIGtn/?ref=app
+ 1
Ipang OK: my bad ^^
+ 1
I á´á´ "TÉŞá´á´" I know now why my algorithm was wrong, some of the keys have the same value so when I swap them, since dictionaries must have distinct keys, it eliminates some of them instead of adding them up in the list
+ 1
Elijah Nwalozie Here's a possible solution:
old_dict = {...} # All the items
new_dict = {a: (k:=[x for x in old_dict if old_dict[x] == a]) * (len(k) > 1) or k[0] for a in old_dict.values()}
# Hope this helps
+ 1
Elijah Nwalozie
Yes dictionary do not allow duplicate keys that is why I have stored duplicate keys value in a list.