37

I'm basically trying to iterate through a dict and print out the key / values from largest value to lowest. I have been searching this site and a lot of people are using lambda but I'm not really sure how its working so I'm trying to avoid it for now.

dictIterator = iter(sorted(bigramDict.iteritems()))
for ngram, value in dictIterator:
    print("There are " + str(value) + " " + ngram)

Looking over the code above I assumed it would make an iterator which returns the key/value pairs in order from largest to smallest but it's not.

Can anyone see what the problem is? or another method of doing this?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Xtrato
  • 455
  • 1
  • 5
  • 7

5 Answers5

34

One can take advantage of the fact that sort works on tuples by considering the first element as more important than the second etc:

d = { "a":4, "c":3, "b":12 }
d_view = [ (v,k) for k,v in d.iteritems() ]
d_view.sort(reverse=True) # natively sort tuples by first element
for v,k in d_view:
    print "%s: %d" % (k,v)

Output:

b: 12
a: 4
c: 3

EDIT: one-liner, generator expression:

sorted( ((v,k) for k,v in d.iteritems()), reverse=True)

Output:

[(12, 'b'), (4, 'a'), (3, 'c')]
oDDsKooL
  • 1,767
  • 20
  • 23
25

You can use the key parameter of sorted to sort by the 2nd item:

>>> d = { "a":4, "c":3, "b":12 }
>>> from operator import itemgetter
>>> for k, v in sorted(d.items(), key=itemgetter(1)):
    print k, v


c 3
a 4
b 12
>>> 

EDIT: one-liner, in opposite order:

>>> d = {"a": 4, "c": 3, "b": 12}
>>> [(k, v) for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True)]
[('b', 12), ('a', 4), ('c', 3)]
>>> 
Emmanuel
  • 13,935
  • 12
  • 50
  • 72
  • These sorts the opposite way. Mind editing to reverse the order (so that it goes from largest to smallest)? Thanks! – Ward W Dec 19 '19 at 03:07
4
>>> d = { "a":4, "c":3, "b":12 }
>>> from operator import itemgetter
>>> lst = sorted(d.iteritems(), key=itemgetter(1))
>>> for t in lst: print '%s : %d' % (t[0], t[1])
... 
c : 3
a : 4
b : 12
number23_cn
  • 4,611
  • 26
  • 31
3

Here's a solution with Python 3:

d = { "a":4, "c":3, "b":12 }
sorted(((v, k) for k, v in d.items()), reverse=True)
jss367
  • 4,759
  • 14
  • 54
  • 76
0
d = { "a":4, "c":3, "b":12 }
for v in sorted( d.values() ):
    for key in d:
        if d[ key ] == v:
            print key, v
            break
shiva
  • 2,674
  • 4
  • 23
  • 37