Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

How to do it...

The following examples are taken from the Python documentation at https://docs.python.org/3/library/collections.html#collections.defaultdict:

  1. A list is a common source for default_factory, as it makes it easy to group a sequence of key:value pairs into a dictionary of lists, as follows:
      >>> from collections import defaultdict      >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]      >>> d = defaultdict(list)            >>> for k, v in s:      ...     d[k].append(v)      ...      >>> sorted(d.items())      [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
    • First, a list of tuples is created. The tuples match a string with an integer.
    • A defaultdict is created using an empty list as the factory argument.
    • The list of tuples is iterated ...
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

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content