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?
First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.
We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With