Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find n largest values from dictionary

I am working in Python project and I have a problem seem as what I explain below but with other data. For example, if I have this dict:

fruitsCount= {"apple": 24, "orange": 20, "banana":18, "grape":13, "kiwi": 13}

how can I return the keys with maximum values ? what if I want to return three largest ?

I used heapq.nlargest(3, fruitCount.values) but I don't know how I return them with their keys

Note: fruitsCount is a dict returned after using Counter() from another dict.

Output: should be same fruitsCount dictionary with n largest fruitsCount.values

like image 362
Nujud Ali Avatar asked May 23 '26 21:05

Nujud Ali


1 Answers

You need to use heapq.nlargest() on the items, and use the key argument to tell it to take the value from that pair:

heapq.nlargest(3, fruitCount.items(), key=lambda i: i[1])

This returns the 3 largest (key, value) pairs.

Or you could just use the collections.Counter() class, which has a most_common() method that does this for you:

Counter(fruitCount).most_common(3)
like image 108
Martijn Pieters Avatar answered May 26 '26 11:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!