Just make a new dictionary using the first N items (key pairs) in the (reverse) ordered dictionary you already have. For example, to get the top three items you could do something like this:
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}
For Python 3 one could use dict(list(ordered.items())[:3])
since items()
returns an iterator in that version. Alternatively you could use dict(itertools.islice(ordered.items(), 3))
which would work in both Python 2 and 3.
Also note the result is just a regular dictionary—as you specified in your question—not a collections.Counter
or other type of mapping. This approach is very general and doesn't require the original dictionary
to have integer values—just things can be ordered (i.e. compared via the key
function).