简体   繁体   中英

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

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)

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]

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM