CAVS CAVS - 1 year ago 108
Python Question

Get n largest key, value in a dictionary

number = 2
dct = {'a': 5,'b': 3,'c': 4}

for key,value in dct.items():

I want to check the values that are the largest in the dictionary. The check depends on the number, so in this case,
{'a':5, 'c':4}
should be returned, since the number is
. However if the number was 1, only
should be returned. I cannot import or use lambda

Answer Source

You can get the nlargest dict.values() and associated keys using a dict comprehension.

>>> import heapq
>>> n = 2
>>> mydict = {'a': 5, 'b': 3, 'c': 4}
>>> {key: value for key, value in mydict.items() if value in heapq.nlargest(n, mydict.values())}
{'a': 5, 'c': 4}

Without importing you can do it like this:

>>> n = 2
>>> mydict = {'a': 5, 'b': 3, 'c': 4}
>>> {key: mydict[key] for key in sorted(mydict, key=mydict.get, reverse=True)[:n]}
{'a': 5, 'c': 4}

The list comprehension is the equivalent of this:

result = {}
for key in sorted(mydict, key=mydict.get, reverse=True)[:n]:
    result.update({key: mydict[key]})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download