What is the best way to implement nested dictionaries?

后端 未结 21 1812
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  温柔的废话
    2020-11-22 00:46

    collections.defaultdict can be sub-classed to make a nested dict. Then add any useful iteration methods to that class.

    >>> from collections import defaultdict
    >>> class nesteddict(defaultdict):
        def __init__(self):
            defaultdict.__init__(self, nesteddict)
        def walk(self):
            for key, value in self.iteritems():
                if isinstance(value, nesteddict):
                    for tup in value.walk():
                        yield (key,) + tup
                else:
                    yield key, value
    
    
    >>> nd = nesteddict()
    >>> nd['new jersey']['mercer county']['plumbers'] = 3
    >>> nd['new jersey']['mercer county']['programmers'] = 81
    >>> nd['new jersey']['middlesex county']['programmers'] = 81
    >>> nd['new jersey']['middlesex county']['salesmen'] = 62
    >>> nd['new york']['queens county']['plumbers'] = 9
    >>> nd['new york']['queens county']['salesmen'] = 36
    >>> for tup in nd.walk():
        print tup
    
    
    ('new jersey', 'mercer county', 'programmers', 81)
    ('new jersey', 'mercer county', 'plumbers', 3)
    ('new jersey', 'middlesex county', 'programmers', 81)
    ('new jersey', 'middlesex county', 'salesmen', 62)
    ('new york', 'queens county', 'salesmen', 36)
    ('new york', 'queens county', 'plumbers', 9)
    

提交回复
热议问题