AttrDict Class make it possible to access Python dictionary with attribute-style, and a recursive translate function.
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 AttrDict(dict): | |
"""A dictionary with attribute-style access. It maps attribute access to | |
the real dictionary. """ | |
def __init__(self, init={}): | |
dict.__init__(self, init) | |
def __getstate__(self): | |
return self.__dict__.items() | |
def __setstate__(self, items): | |
for key, val in items: | |
self.__dict__[key] = val | |
def __repr__(self): | |
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self)) | |
def __setitem__(self, key, value): | |
return super(AttrDict, self).__setitem__(key, value) | |
def __getitem__(self, name): | |
return super(AttrDict, self).__getitem__(name) | |
def __delitem__(self, name): | |
return super(AttrDict, self).__delitem__(name) | |
__getattr__ = __getitem__ | |
__setattr__ = __setitem__ | |
def recursive_attrdict(obj): | |
"""Walks a simple data structure, converting dictionary to AttrDict. | |
Supports lists, tuples, and dictionaries. | |
""" | |
if isinstance(obj, dict): | |
return AttrDict(dict((str(k), recursive_attrdict(v)) for (k, v) in obj.items())) | |
elif isinstance(obj, list): | |
return list(recursive_attrdict(i) for i in obj) | |
elif isinstance(obj, tuple): | |
return tuple(recursive_attrdict(i) for i in obj) | |
else: | |
return obj |
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
import attrdict | |
obj = { | |
'A':{ | |
'A1':{ | |
'A11' : [{'a':'this is a'}, {'b':'this is b'}], | |
'A12' : [{'a2':'this is a2'}, {'b2':'this is b2'}] | |
}, | |
'A2':[12, 324, 34.23, None] | |
} | |
} | |
adobj = attrdict.recursive_attrdict(obj) | |
print(adobj) | |
print(adobj.A.A1.A11[1].b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
very nice done. I was thinking about doing this my own, but this works like charme.
However, ipythons autocompletion won´t find the attributes of an Attrdict object. But that was initially my main idea why accessing dictionary keys as attributes would be nice :).
Regards
Legout