collections. defaultdict
A dictionary that creates a default value on its own for a missing key, e.g. an empty list or zero.
- Returns
- A
defaultdictobject, that is a dictionary with automatic default values.
Example
#from collections import defaultdict
topics = [("HTML", "tags"), ("CSS", "flexbox"), ("HTML", "forms")]
by_course = defaultdict(list)
for course, topic in topics:
by_course[course].append(topic)
print(by_course["HTML"])
print(dict(by_course))Definition and usage
#The defaultdict class from the collections module works like an ordinary dictionary, but when you read a missing key it does not raise KeyError. Instead, it calls the function given at creation, stores the result under that key, and returns it.
You pass the function without parentheses: defaultdict(list) creates an empty list for new keys, defaultdict(int) zero, and defaultdict(set) an empty set. You can also pass your own function, e.g. defaultdict(lambda: "none").
The most common uses are grouping (groups[key].append(item)) and summing (totals[key] += value) without checking whether the key already exists. Remember that simply reading d[key] also adds the missing key. The get() method and the in operator do not.
Syntax
#from collections import defaultdict
defaultdict(default_factory)
defaultdict(list)
defaultdict(int)Parameters
#default_factory
function with no arguments, or None
Creates the value for a missing key, e.g.listgives[], andintgives0. WithNone, the dictionary behaves like an ordinarydict.
More examples
#from collections import defaultdict
points = defaultdict(int)
for name, exp in [("Emma", 20), ("Jack", 15), ("Emma", 10)]:
points[name] += exp
print(points)
print(points["Mia"])from collections import defaultdict
scores = defaultdict(list)
print(scores["Mia"])
print("Mia" in scores, len(scores))
print(scores.get("Zoe"), len(scores))Good practices
#- To check whether a key exists, use
inorget(). Reading through square brackets will add the missing key. - Before passing the result on, convert it to an ordinary dictionary with
dict(). It prints more clearly, and an accidental read of a missing key will no longer add a new entry. - For simply counting items,
Counteris even more convenient.
Related entries
#- collections.CounterA dictionary for counting: for each item, it stores the number of times it occurs.
- dict.setdefault()Returns the value of a key, and first stores a default value in the dictionary when the key is missing.
- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
- list.append()Adds one item to the end of a list.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
Spotted a mistake or missing an example? Write to us.