Skip to content

Instantly share code, notes, and snippets.

@brouberol
Last active August 29, 2015 14:19
Show Gist options
  • Save brouberol/1cb2fbfe5bde11237c91 to your computer and use it in GitHub Desktop.
Save brouberol/1cb2fbfe5bde11237c91 to your computer and use it in GitHub Desktop.
Meet CoolDict: a python dict that always keeps its cool.
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