How to get all the keys with the same highest value?

前端 未结 3 591
予麋鹿
予麋鹿 2020-12-16 01:11

If I have a dictionary with their corresponding frequency values:

numbers = {a: 1, b: 4, c: 1, d: 3, e: 3}

To find the highest, what I know

相关标签:
3条回答
  • 2020-12-16 01:38

    The collections.Counter object is useful for this as well. It gives you a .most_common() method which will given you the keys and counts of all available values:

    from collections import Counter
    numbers = Counter({'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3})
    values = list(numbers.values())
    max_value = max(values)
    count = values.count(max_value)
    numbers.most_common(n=count)
    
    0 讨论(0)
  • 2020-12-16 01:46
    numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
    max_value = max(numbers.values())
    
    
    [k for k,v in numbers.iteritems() if v == max_value]
    

    prints

     ['e', 'd']
    

    what it does is, loop over all entries via .iteritems and then check if the value is the maximum and if so add the key to a list.

    0 讨论(0)
  • 2020-12-16 02:00
    numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
    mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
    max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value
    
    print(max_list)
    

    This code will work in O(n). O(n) in finding maximum value and O(n) in the list comprehension. So overall it will remain O(n).

    Note : O(2n) is equivalent to O(n).

    0 讨论(0)
提交回复
热议问题