collections.defaultdict

suggest change

collections.defaultdict(default_factory) returns a subclass of dict that has a default value for missing keys. The argument should be a function that returns the default value when called with no arguments. If there is nothing passed, it defaults to None.

>>> state_capitals = collections.defaultdict(str)
>>> state_capitals
defaultdict(<class 'str'>, {})

returns a reference to a defaultdict that will create a string object with its default_factory method.

A typical usage of defaultdict is to use one of the builtin types such as str, int, list or dict as the default_factory, since these return empty types when called with no arguments:

>>> str()
''
>>> int()
0
>>> list
[]

Calling the defaultdict with a key that does not exist does not produce an error as it would in a normal dictionary.

>>> state_capitals['Alaska']
''
>>> state_capitals
defaultdict(<class 'str'>, {'Alaska': ''})

Another example with int:

>>> fruit_counts = defaultdict(int)
>>> fruit_counts['apple'] += 2  # No errors should occur
>>> fruit_counts
default_dict(int, {'apple': 2})
>>> fruit_counts['banana']  # No errors should occur
0
>>> fruit_counts  # A new key is created
default_dict(int, {'apple': 2, 'banana': 0})

Normal dictionary methods work with the default dictionary

>>> state_capitals['Alabama'] = 'Montgomery'
>>> state_capitals
defaultdict(<class 'str'>, {'Alabama': 'Montgomery', 'Alaska': ''})

Using list as the default_factory will create a list for each new key.

>>> s = [('NC', 'Raleigh'), ('VA', 'Richmond'), ('WA', 'Seattle'), ('NC', 'Asheville')]
>>> dd = collections.defaultdict(list)
>>> for k, v in s:
...     dd[k].append(v)
>>> dd
defaultdict(<class 'list'>, 
    {'VA': ['Richmond'], 
     'NC': ['Raleigh', 'Asheville'], 
     'WA': ['Seattle']})

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Collections module:
* collections.defaultdict

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
32 Collections module
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve