Skip to content

Instantly share code, notes, and snippets.

@tanbro
Last active Jun 24, 2022
Embed
What would you like to do?
AttrDict Class make it possible to access Python dictionary with attribute-style, and a recursive translate function.
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
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)
@legout
Copy link

legout commented Oct 24, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment