How can I find the most repetitive value in a dictionnary? For instance:
[In] tree = {1:2,3:2,4:2,4:3}
[Out] 2
How can I find the most repetitive value in a dictionnary? For instance:
[In] tree = {1:2,3:2,4:2,4:3}
[Out] 2
from collections import Counter
tree = {1:2,3:2,4:2,4:3}
value, count = Counter(tree.values()).most_common(1)[0]
# 'value' is the most common value
# 'count' is how many times it appears
While using inbuild libraries is good, we can implement using basic components
tree = {1:2,3:2,4:2,4:3,7:2}
d = {}
for k in tree.values():
if(k in d):
d[k] += 1
else:
d[k] = 1
max_val = None
k_of_max_val = None
for k in d:
if(max_val != None):
if(d[k] > max_val):
k_of_max_val = k
max_val = d[k]
else:
k_of_max_val = k
max_val = d[k]
print(f'{k_of_max_val} occured maximum with {max_val} times')
output
2 occured maximum with 3 times