Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 2. However if the number was 1, only {'a':5} should be returned. I cannot import or use lambda

like image 516
Monty Avatar asked Feb 06 '23 15:02

Monty


1 Answers

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

If multiple keys have the same value and you want to break the n largest rule then you need to use set.

>>> mydict = {'a': 5, 'b': 3, 'c': 4, 'd': 4}
>>> {key: value for key, value in mydict.items() if value in sorted(set(mydict.values()), reverse=True)[:2]}
{'a': 5, 'c': 4, 'd': 4}

You can also 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}
like image 178
styvane Avatar answered Feb 08 '23 17:02

styvane