Get first N key pairs from an Ordered Dictionary to another one

Nihar Sarangi picture Nihar Sarangi · Nov 27, 2011 · Viewed 15.4k times · Source

I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary? For example: I have something like this:

dictionary={'a':10,'b':20,'c':30,'d':5}
ordered=OrderedDict(sorted(dictionary.items(), key=lambda x: x[1],reverse=True))

Now ordered is an ordered dictionary, I want to create a dictionary, say by taking the top 2 most-frequent items and their keys:

frequent={'c':30,'b':20}

Answer

Beni Cherniavsky-Paskin picture Beni Cherniavsky-Paskin · Nov 28, 2011

The primary purpose of collections.OrderedDict is retaining the order in which the elements were inserted.
What you want here is collections.Counter, which has the n-most-frequent functionality built-in:

>>> dictionary={'a':10,'b':20,'c':30,'d':5}
>>> import collections
>>> collections.Counter(dictionary).most_common(2)
[('c', 30), ('b', 20)]