Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}
like image 521
Nihar Sarangi Avatar asked Nov 27 '11 16:11

Nihar Sarangi


People also ask

How do you find the first N in a dictionary?

You can get dictionary items by calling . items() on the dictionary. then convert that to a list and from there get first N items as you would on any list. e.g.

How do I find the first key-value pair in a dictionary?

In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. If you only care about getting the first value of a dictionary, you can use the dictionary values() function.


1 Answers

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)]
like image 84
Beni Cherniavsky-Paskin Avatar answered Sep 21 '22 08:09

Beni Cherniavsky-Paskin