python - Subclassing dict and nested dicts in it -
i have nested dictionary want convert next subclass did:
class subdict(dict): def __getattr__(self, attr): if attr in self.keys(): homecoming self.get(attr)
and if do, works great base of operations dict :
my_nested_dict = subdict(my_nested_dict)
but need nested ones converted subdict too. how accomplish that?
thanks!
you need recurse on nested dictionaries , convert recursively:
class subdict(dict): def __init__(self, *args, **kw): super(subdict, self).__init__(*args, **kw) key, value in self.iteritems(): if isinstance(value, dict): self[key] = subdict(value)
have looked collections.defaultdict
@ all? can create tree scratch quite easily:
import defaultdict def tree(): homecoming defaultdict(tree)
python dictionary python-2.7 override subclass
No comments:
Post a Comment