5

I have a dict d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'}. I want to sort the dict with numeric value of d.values(). Required ans is ['a','f', 'g', 'b', 'c', 'e']. I had checked here . I couldn't make it to sort according to integer value of d.values().

Community
  • 1
  • 1
Netro
  • 7,119
  • 6
  • 40
  • 58

2 Answers2

12
>>> d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'}
>>> sorted(d, key=lambda i: int(d[i]))
['a', 'f', 'g', 'b', 'c', 'e']
Volatility
  • 31,232
  • 10
  • 80
  • 89
0

That's because the values in your dictionary are of type string: note the quotes around the numbers. Try setting your dictionary as:

d = {'a':1, 'c':10, 'b':8, 'e':11, 'g':3, 'f':2}
sjbx
  • 1,205
  • 2
  • 12
  • 12