Title: Create Counts Of Items
Slug: creating_counts_of_items
Summary: Create Counts Of Items in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Interesting in learning more? Check out Fluent Python
In [1]:
from collections import Counter
In [2]:
# Create a counter of the fruits eaten today
fruit_eaten = Counter(['Apple', 'Apple', 'Apple', 'Banana', 'Pear', 'Pineapple'])
# View counter
fruit_eaten
Out[2]:
In [3]:
# Update the count for 'Pineapple' (because you just ate an pineapple)
fruit_eaten.update(['Pineapple'])
# View the counter
fruit_eaten
Out[3]:
In [4]:
# View the items with the top 3 counts
fruit_eaten.most_common(3)
Out[4]: