Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading