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}
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.
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.
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)]
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