Created
November 13, 2019 22:25
-
-
Save tjvananne/223e8d91d4dfdcba5622e1c9259478ae to your computer and use it in GitHub Desktop.
Python defaultdict - simplest demonstration of why it matters
This file contains hidden or 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
# Python 3.7 was used for this gist - it should work on many different versions (not going to enumerate them here) | |
# I don't really like the docs for defaultdict. maybe they're more rigorous than this definition | |
# i think this micro-example captures the essense of when/why to use defaultdict. | |
import collections | |
# create a normal dictionary and a defaultdict so we can compare functionality | |
d = {} | |
dd = collections.defaultdict(list) | |
# both dicts are empty at this point | |
# attempt to append a value to a key within the dict (note that the key does not yet exist in either case) | |
# d['x'].append('hello') # <-- KeyError; this doesn't work... | |
dd['x'].append('world') # <-- dd['x'] is now a list equal to `['world']` | |
# print our dicts to see what they contain | |
print(d) # <-- empty because we commented it out to prevent it from erroring | |
print(dd) # <-- ['world'] | |
# why is this cool does this matter? | |
# If we want to capture a list for each key in our dictionary, then defaultdict helps so we don't have to test for key existence | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment