-4

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

Joseph
  • 69
  • 4
  • 13

3 Answers3

2
>>> 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)])
user3557327
  • 1,109
  • 13
  • 22
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]
Tasos
  • 7,325
  • 18
  • 83
  • 176
2

Use the sorted function.

d = dict(red=2, blue=45, green=100)
sorted(d.items(), key=lambda a: a[1], reverse=True)   
BDurand
  • 108
  • 1
  • 10