Today I Learned

hashrocket A Hashrocket project

Counting is as easy as...

Python has a specialized dict data structure for a common task, counting. Counter can process and store the counts of items you pass it.

Initialized like this with chars, and then keys:

from collections import Counter

char_count = Counter('xyxxyxyy')
# Counter({'x': 4, 'y': 4})

keys_count = Counter({'apple': 2, 'banana': 5, 'pear': 3})
# Counter({'banana': 5, 'pear': 3, 'apple': 2})

Then updating the Counter is easy with update:

chars_count.update('abxyabxy')
# Counter({'x': 6, 'y': 6, 'a': 2, 'b': 2})

keys_count.update({'apple': 1, 'banana': 2, 'fruit': 3})
# Counter({'banana': 7, 'apple': 3, 'pear': 3, 'fruit': 3})

Then figure out which items are the most common:

chars_count.most_common(2)
# [('x', 6), ('y', 6)]
keys_count.most_common(2)
# [('banana', 7), ('apple', 3)]

Read more about some really useful things you can do with counter objects in the Python docs

See More #python TILs