简体   繁体   中英

Python Dict more than one Max value

I am using a list to find a max value from a group of items in the list using the line: x=max(dictionary, key=dictionary.get) This works fine unless two or more values in the dictionary are the same, it just seems to choose one of the max at complete random. Is there a way that I can get it to print both of the max values, possibly in a list eg: dictionary={'A':2,'B':1,'C':2} which will return x=['A','C']

>>> dictionary = { 'A': 2, 'B': 1, 'C': 2 }
>>> maxValue = max(dictionary.values())
>>> [k for k, v in dictionary.items() if v == maxValue]
['C', 'A']

You can also use a counter to get the items sorted by “most common” (highest value):

>>> from collections import Counter
>>> c = Counter(dictionary)
>>> c.most_common()
[('C', 2), ('A', 2), ('B', 1)]

Unfortunately, the parameter n to most_common gives you n maximum elements, and not all with the maximum value, so you need to filter them manually, eg using itertools.takewhile :

>>> from itertools import takewhile
>>> maxValue = c.most_common(1)[0][1]
>>> list(takewhile(lambda x: x[1] == maxValue, c.most_common()))
[('C', 2), ('A', 2)]

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