Pls how do I reverse a dictionary? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

4th Jul 2021, 11:30 PM
Nwalozie Elijah
Nwalozie Elijah - avatar
8 Answers
+ 4
Elijah Nwalozie There is lots of ways to swap Key Value of dictionary. https://code.sololearn.com/cyW0S7hPc9eV/?ref=app
5th Jul 2021, 3:24 AM
A͢J
A͢J - avatar
+ 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})
5th Jul 2021, 12:04 AM
Abhay
Abhay - avatar
+ 2
Calvin Thomas I'll try this too thanks
5th Jul 2021, 6:27 AM
Nwalozie Elijah
Nwalozie Elijah - avatar
+ 1
You can also use dictionary comprehension https://code.sololearn.com/cDkQNzkcIGtn/?ref=app
5th Jul 2021, 12:37 AM
Ipang
+ 1
Ipang OK: my bad ^^
5th Jul 2021, 1:47 AM
visph
visph - avatar
+ 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
5th Jul 2021, 6:06 AM
Nwalozie Elijah
Nwalozie Elijah - avatar
+ 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
5th Jul 2021, 6:14 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Elijah Nwalozie Yes dictionary do not allow duplicate keys that is why I have stored duplicate keys value in a list.
5th Jul 2021, 7:01 AM
A͢J
A͢J - avatar