Last active
August 29, 2015 14:19
-
-
Save brouberol/1cb2fbfe5bde11237c91 to your computer and use it in GitHub Desktop.
Meet CoolDict: a python dict that always keeps its cool.
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
class CoolDict(dict): | |
"""A dict that returns an empty CoolDict if a key is not found. | |
It litterally goes: 'Can't find your thing, but that's cool, don't care.' | |
Example: | |
>>> d = CoolDict() | |
>>> d['value1']['value2'].get('value3', 0) | |
0 | |
That could be very useful when dealing with JSON APIs with unreliable content, | |
by saving you a ton of try/excepts. | |
""" | |
def __getitem__(self, key): | |
try: | |
return super(CoolDict, self).__getitem__(key) | |
except KeyError: | |
return CoolDict() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment