Megaslav
Megaslav

Reputation: 15

Subclassing dict and nested dicts in it

I have a nested dictionary that I want to convert to the following subclass I did:

class SubDict(dict):
    def __getattr__(self, attr):
        if attr in self.keys():
            return self.get(attr)

And if I do, it works great for the base dict :

my_nested_dict = SubDict(my_nested_dict)

But I need the nested ones converted to SubDict too. How could I achieve that?

Thanks!

Upvotes: 0

Views: 526

Answers (2)

akaIDIOT
akaIDIOT

Reputation: 9231

If your SubDict class does nothing other than what you show here, this is a job for defaultdict as document by Harold Cooper on Github:

def tree(): return defaultdict(tree)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121644

You need to recurse over the nested dictionaries and convert those recursively:

class SubDict(dict):
    def __init__(self, *args, **kw):
        super(SubDict, self).__init__(*args, **kw)
        for key, value in self.iteritems():
            if isinstance(value, dict):
                self[key] = SubDict(value)

Have you looked into collections.defaultdict at all? You can create a tree from scratch with that quite easily:

import defaultdict

def Tree(): return defaultdict(tree)

Upvotes: 1

Related Questions