Search code examples
pythondictionarymax

Getting all keys with highest value in a dictionary


In python dictionary, how to search the max value and return the key of the max value in a list. For instance, 3 is the max value in this dictionary. Given:

Frequency = {9: 3, 2: 3, 6: 2, 8: 1, 1: 1} Output: [9, 2]

def max_value(dict):
    for key, value in dict.items():
    max_value = max(dict.values())
    new_list = []
    if frequency[key] == max_value:
        new_list.append(key)
    return new_list

With this function, I can only get one key inside the new_list. I am expecting to get [9, 2]


Solution

  • Find the max value before the for loop:

    def keys_with_max_value(d: dict[int, int]) -> list[int]:
        max_value = max(d.values())
        max_value_keys = []
        for key, value in d.items():
            if value == max_value:
                max_value_keys.append(key)
        return max_value_keys
    

    Example Usage:

    frequency = {9: 3, 2: 3, 6: 2, 8: 1, 1: 1}
    print(keys_with_max_value(frequency))  # Output: [9, 2]