Skip to content

Instantly share code, notes, and snippets.

@noamtm
Last active May 29, 2018 20:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamtm/9758122 to your computer and use it in GitHub Desktop.
Save noamtm/9758122 to your computer and use it in GitHub Desktop.
Python: read-only access to dictionary keys as attributes
# There are other solutions across the interwebs. This is one that avoids complexities
# because it's read-only (useful when you just want to read json data, for example).
# It also makes it possible to read nested dictionaries in the same way.
# Based on ideas from http://code.activestate.com/recipes/473786-dictionary-with-attribute-style-access/
class attrdict (dict):
'''
Read-only access to dictionary keys as attributes.
>>> d=attrdict({"a":1, "b":2, "c":{"a":1, "b":2, "c":{"a":1, "b":2}}})
>>> d.a
1
>>> d.b
2
>>> d.c
{'a': 1, 'c': {'a': 1, 'b': 2}, 'b': 2}
>>> d.c.a
1
>>> d.c.c
{'a': 1, 'b': 2}
>>> d.c.c.a
1
'''
def __getitem__(self, key):
value = dict.__getitem__(self, key)
return attrdict(value) if isinstance(value, dict) else value
__getattr__ = __getitem__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment