I want to sort a dictionary by value in reverse order. For example: [Red: 2, Blue: 45, Green: 100] to print Green 100, Blue 45, Red 2
Thanks
I want to sort a dictionary by value in reverse order. For example: [Red: 2, Blue: 45, Green: 100] to print Green 100, Blue 45, Red 2
Thanks
>>> from collections import OrderedDict
>>> a = {"Red": 2, "Blue": 45, "Green": 100}
>>> OrderedDict(sorted(a.items(), key=lambda x: x[1], reverse=True))
OrderedDict([('Green', 100), ('Blue', 45), ('Red', 2)])
You have used the Python tag but the dictionary is not a valid Python Dictionary. This is the right structure:
{"Red": 2, "Blue": 45, "Green": 100}
So, if you want to print it here is another way:
mydic = {"Red": 2, "Blue": 45, "Green": 100}
for w in sorted(mydic, key=mydic.get, reverse=True):
print w, mydic[w]
Use the sorted function.
d = dict(red=2, blue=45, green=100)
sorted(d.items(), key=lambda a: a[1], reverse=True)