Nujud Ali
Nujud Ali

Reputation: 135

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

Upvotes: 3

Views: 6111

Answers (4)

Manu Manoj
Manu Manoj

Reputation: 399

You can try this one. Your answer will be apple, orange, banana.

heapq.nlargest(3, d, key=fruitsCount.get)

Time complexity in this approach will be nlog(t). N is the number of elements in the dictionary and t is the number of elements you want. In the above case, t is 3.

Upvotes: 1

md kamran
md kamran

Reputation: 1

New to python not very sure about the shortcut, but here is my answer:

from heapq import nlargest

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

Reverse the key value pairs so that sorting is done wrt values:

fruitsCount = {j:i for i,j in fruitsCount.items()}

Find the largest 3 items in a separate dictionary:

x = dict(nlargest(3,fruitsCount.items()))

Reverse the dictionary back to original form:

x = {z:y for y,z in x.items()}
print(x)

Upvotes: 0

Iron Pillow
Iron Pillow

Reputation: 2202

Having never used the heapq module, I prefer this module-free approach:

sorted( fruitsCount.items(), key=lambda pair: pair[1], reverse=True )[:3]

Smaller, but less clear:

sorted( fruitsCount.items(), key=lambda pair: -pair[1] )[:3]

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121724

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)

Upvotes: 6

Related Questions