Reputation:
In a dictionary with keys and a list of values, how do you find which value is in the lists of values most frequently? I'm assuming you use for loops and append to lists but am unsure of how to do so. Also I want to print the value which is occurring most frequently?
Thank you!
Please keep in mind I'm very new to programming and am not familiar with lambda or other complicated ways to solve this.
Upvotes: 1
Views: 120
Reputation: 2562
Sorting the dictionary by value should do it:
d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
print(d[sorted(d, key=lambda k: d[k])[-1]])
Cyber is right, the above gets the largest value. See below to get the most frequent. My idea is to get the value without using the collections.Counter.
counts = {}
for k in d:
counts[d[k]] = counts.get(d[k], 0) + 1
print(sorted(counts)[-1]) # 5
print(counts) # {1: 1, 3: 1, 5: 3}
Upvotes: 0
Reputation: 117856
One way to do so would be to use collections.Counter
from collections import Counter
>>> d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
>>> c = Counter(d.values())
>>> c
[(5, 3), (1, 1), (3, 1)]
>>> c.most_common()[0]
(5, 3) # this is the value, and number of appearances
Upvotes: 5