Last active
April 20, 2022 18:44
-
-
Save FerusAndBeyond/7960762a8b7043121a0f7acbd0bf5063 to your computer and use it in GitHub Desktop.
Default-dicts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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