I am trying to write a function that returns the most frequent value in a dictionary in Python. I do not want to import anything, just simple code.
Any ideas? For example, if my dictionary is:
input_dict = {'A': 1963, 'B': 1963,
'C': 1964, 'D': 1964, 'E': 1964,
'F': 1965, 'G': 1965, 'H': 1966,
'I': 1967, 'J': 1967, 'K': 1968,
'L': 1969 ,'M': 1969,
'N': 1970}
The expected result is 1964
(because it is present as the value in the dict
3 times (maximum count)).
This was my last attempt:
def most_prolific(input_dict):
values = []
for year in input_dict.values():
if year in input_dict.values():
values.append(year)
for most in values:
if most in values:
return max(values.count(most))
collections.Counter
:Simplest way to achieve this is via using Python's builtin collections.Counter
which is created for the same purpose. Here's the sample code for your example:
from collections import Counter
input_dict = {'A': 1963, 'B': 1963, 'C': 1964, 'D': 1964, 'E': 1964, 'F': 1965, 'G': 1965, 'H': 1966, 'I': 1967, 'J': 1967, 'K': 1968, 'L': 1969 ,'M': 1969, 'N': 1970}
value, count = Counter(input_dict.values()).most_common(1)[0]
# in above code, `value` will hold value `1964` <--- one you desire
# and `count` will hold value `3`
Here's another one without importing any module. Here I am creating my own counter using dict
as:
my_counter_dict = {}
for v in input_dict.values():
my_counter_dict[v] = my_counter_dict.get(v, 0)+1
# Value hold by `my_counter_dict`:
# {1963: 2, 1964: 3, 1965: 2, 1966: 1, 1967: 2, 1968: 1, 1969: 2, 1970: 1}
From the above dict
, extract the key with maximum value using max
function as:
>>> max(my_counter_dict.iterkeys(), key=my_counter_dict.get)
1964
Here's another alternative without creating the intermediate dictionary, but it is relatively less efficient because of one complete iteration of the list due to the list.count
for each element in list:
>>> values_list = list(input_dict.values())
>>> max(set(values_list), key=values_list.count)
1964
Even i suggest you don't need to import anything , its simple task :
input_dict = {'A': 1963, 'B': 1963,
'C': 1964, 'D': 1964, 'E': 1964,
'F': 1965, 'G': 1965, 'H': 1966,
'I': 1967, 'J': 1967, 'K': 1968,
'L': 1969 ,'M': 1969,
'N': 1970}
track={}
for key,value in input_dict.items():
if value not in track:
track[value]=0
else:
track[value]+=1
print(max(track,key=track.get))
output:
1964
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With