Python Counting - finding the most common occurence
Python tip:
You can use
Counter
from thecollections
module to find the most common element in a:
- string - character with the most occurrences
- dict - key with highest value
- list - element with the most occurrences
most_common(n)
-> returns n most common elementfrom collections import Counter counter = Counter("TestDriven.io tutorials") print(counter.most_common(1)) # character with the most occurrences # => [('t', 3)] counter = Counter({"red": 2, "green": 10, "blue": 7}) print(counter.most_common(1)) # key with the highest value # => [('green', 10)] counter = Counter([0, 2, 1, 1, 4, 10, 33, 21, 12, 10, 1]) print(counter.most_common(1)) # element with the most occurrences # => [(1, 3)]