Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

Counter

You'd think that you couldn't get much simpler than defaultdict(int), but the I want to count specific instances in an iterable use case is common enough that the Python developers created a specific class for it. The previous code that counts characters in a string can easily be calculated in a single line:

from collections import Counter 
def letter_frequency(sentence): 
    return Counter(sentence) 

The Counter object behaves like a beefed-up dictionary where the keys are the items being counted and the values are the quantities of such items. One of the most useful functions is the most_common() method. It returns a list of (key, count) tuples ordered by the count. You can optionally pass an integer argument into most_common() to request ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content