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