-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
MrSpaar
  • 3,979
  • 2
  • 10
  • 25
aria
  • 3
  • 1

2 Answers2

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 
Aven Desta
  • 2,114
  • 12
  • 27
0

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
Epsi95
  • 8,832
  • 1
  • 16
  • 34