Reputation: 115
I have a defaultdict that is storing the count of names that appear in a list. The dictionary is as follows:
{"John": 5, "Jim": 2, "Zack": 1, "Brian": 5, "Tim": 3}
How can I efficiently return a dictionary that only contains the max value? In this case, since there is a tie, I'm looking for the final result to be:
{"John": 5, "Brian": 5}
I know I could loop through the original dictionary to accomplish this but I'm curious if there is a more pythonic way to go about it.
Upvotes: 0
Views: 51
Reputation:
mm = {"John": 5, "Jim": 2, "Zack": 1, "Brian": 5, "Tim": 3}
def keys_with_top_values(my_dict):
return [key for (key, value) in my_dict.items() if value == max(my_dict.values())]
print(keys_with_top_values(mm))
Upvotes: 0
Reputation: 634
You can use this as a method to select only the maximum values:
dict1 = {"John": 5, "Jim": 2, "Zack": 1, "Brian": 5, "Tim": 3}
max1 = max(dict1.values())
dict2 = dict(filter(lambda elem: elem[1] == max1, dict1.items()))
print(dict2)
Basically, it first finds out the maximum value out of the dictionary and then filters out the entries which match with the highest value.
Upvotes: 2