Create Counts Of Items

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

Interesting in learning more? Check out Fluent Python


from collections import Counter

Create A Counter

# Create a counter of the fruits eaten today
fruit_eaten = Counter(['Apple', 'Apple', 'Apple', 'Banana', 'Pear', 'Pineapple'])

# View counter
Counter({'Apple': 3, 'Banana': 1, 'Pear': 1, 'Pineapple': 1})

Update The Count For An Element

# Update the count for 'Pineapple' (because you just ate an pineapple)

# View the counter
Counter({'Apple': 3, 'Banana': 1, 'Pear': 1, 'Pineapple': 2})

View The Items With The Highest Counts

# View the items with the top 3 counts
[('Apple', 3), ('Pineapple', 2), ('Banana', 1)]