-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
  • 959
  • 11
  • 22
2

Use the sorted function.

d = dict(red=2, blue=45, green=100)
sorted(d.items(), cmp=lambda a,b: cmp(a[1], b[1]), reverse=True)       
1

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
  • 6,883
  • 13
  • 73
  • 166