Ton Le
Ton Le

Reputation: 25

How do I print multiple dictionary keys which have the same value using the max() function

so lets say i have a dictionary that contains multiple max values for different keys. I tried to use the code:

    taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
    print(max(taste, key=taste.get))

but it only gives me either Mussels or limpets, depending on which one comes first. I tried to set the highest value, then iterate through my keys and for each key, my values such as:

    highest = max(taste.values())
    for i in taste.keys():
      for j in taste[i]:
        if j == highest:
          print(i)

but that doesnt seem to work because you can't interate through integers like the values in my dictionary. So what is the cleanest and most simple way to do this

Upvotes: 0

Views: 1703

Answers (4)

jordeu
jordeu

Reputation: 6821

This solution is using Python3:

maxkeys = [k for k, v in taste.items() if v == max(taste.values())]

Upvotes: 0

Dav
Dav

Reputation: 26

This is what I would do :

highest_value = max(taste.itervalues())
print [key for key, value in taste.iteritems() if value == highest_value]

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174662

As you have multiple values that are the max for the set, you need to be a bit smart in how you filter out all the keys with the same value.

This is more of a sort operation, not a max operation.

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
>>> ordered_by_rating = sorted(list(taste.items()), key=lambda x: x[1], reverse=True)
>>> top_rating = max(ordered_by_rating, key=lambda x: x[1])[1]
>>> only_top = [x[0] for x in filter(lambda x: x[1] == top_rating, ordered_by_rating)]
>>> only_top
['Mussels', 'Limpets']

You can compress the above, by reducing the number of loops you have to go through:

>>> [k for k,v in taste.items() if v == max(taste.values())]
['Mussels', 'Limpets']

Upvotes: 0

Sede
Sede

Reputation: 61253

You can use list comprehensions.

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1}
>>> highest = max(taste.values())
>>> [k for k, v in taste.items() if v == highest]
['Limpets', 'Mussels']

or

>>> for i in taste.keys():
...     if taste[i] == highest:
...         print(i)
... 
Limpets
Mussels

Upvotes: 0

Related Questions