Get the first N key pairs from an ordered dictionary to another

I have an ordered dictionary ( OrderedDict) sorted by value. How to get 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 orderedthis is an ordered dictionary, I want to create a dictionary, say, by selecting the two most commonly used elements and their keys:

frequent={'c':30,'b':20}
+8
source share
4 answers

collections.OrderedDict - , .
, , collections.Counter, n- :

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

, N ( ) () , . , , - :

from collections import OrderedDict
from operator import itemgetter

# create dictionary you have
dictionary = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
ordered = OrderedDict(sorted(dictionary.items(), key=itemgetter(1), reverse=True))

topthree = dict(ordered.items()[:3])
print(topthree) # -> {'a': 10, 'c': 30, 'b': 20}

Python 3 dict(list(ordered.items())[:3]) items() . dict(itertools.islice(ordered.items(), 3)) Python 2, 3.

, , , collections.Counter . , dictionary - (.. key ).

+5

, n- ? , ,

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

ordered.iteritems().

, N , islice itertools.

>>> import itertools
>>> toptwo = itertools.islice(ordered.iteritems(), 2)
>>> list(toptwo)
[('c', 30), ('b', 20)]
>>>
+1

All Articles