For a dictionary of lists, consider a defaultdict
.
A normal dictionary works fine, but it raises an error if a key is not found.
list1 = list("abcd")
list2 = [1, 2, 3, 4]
d = {"list1": list1, "list2": list2}
d["list3"]
# KeyError: 'list3'
This may be disruptive in some applications and may require additional exception handling.
The defaultdict
behaves like a normal dict while adding some protection against errors.
import collections as ct
dd = ct.defaultdict(list)
dd.update(d)
dd
# defaultdict(list, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})
Adding a missing key will call the default factory function, i.e. list
. Here instead of a error, we get an empty container:
dd["list3"]
# []
This entry was added with an empty list.
dd
# defaultdict(list,
# {'list1': ['a', 'b', 'c', 'd'],
# 'list2': [1, 2, 3, 4],
# 'list3': []})
Convert a defaultdict
to a regular dict by setting the default factory to None
dd.default_factory = None
dd
# defaultdict(None, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})
or by using the dict()
builtin:
dict(dd)
# {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]}