Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Last active April 20, 2022 18:44
Show Gist options
  • Save FerusAndBeyond/7960762a8b7043121a0f7acbd0bf5063 to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/7960762a8b7043121a0f7acbd0bf5063 to your computer and use it in GitHub Desktop.
Default-dicts
from collections import defaultdict
# by default a dict
a = defaultdict(dict)
assert a[5] == {}
a[5]["a"] = 5
assert a[5] == { "a": 5 }
# by default a list
a = defaultdict(list)
assert a[5] == []
a[5].append(3)
assert a[5] == [3]
# you can also specify a lambda-expression
# to create the default value
a = defaultdict(lambda: 10)
assert a[5] == 10
assert a[6] + 1 == 11
# in essense, this way we can avoid doing
# if key not in a:
# a[key] = ...
# and it can get especially useful if things are nested
a = defaultdict(lambda: defaultdict(dict))
assert a[5][5] == {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment