defaultdict

  • Returns a new dictionary-like object
  • overrides one method and adds one writable instance variable
  • the remaining functionality is the same as for the dict class
  • the type of the value for each key can be specified

Initialization

In [ ]:
from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list) # each value is a list
for k, v in s:
    d[k].append(v)
    
print(sorted(d.items())) #[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
In [ ]:
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(dict) # each value is a dict
for k, v in s:
    d[k][v] = 0
    
print(sorted(d.items())) # [('blue', {2: 0, 4: 0}), ('red', {1: 0}), ('yellow', {1: 0, 3: 0})]

Dict Methods

In [ ]:
k = d.keys()
print(list(k)) # ['yellow', 'blue', 'red']

v = d.values()
print(list(v)) # [{1: 0, 3: 0}, {2: 0, 4: 0}, {1: 0}]

i = d.items()
print(list(i)) # [('yellow', {1: 0, 3: 0}), ('blue', {2: 0, 4: 0}), ('red', {1: 0})]

Built-in Functions

In [ ]:
print(len(d)) # 3