What is the best way to implement nested dictionaries?

后端 未结 21 2118
[愿得一人]
[愿得一人] 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:53

    class AutoVivification(dict):
        """Implementation of perl's autovivification feature."""
        def __getitem__(self, item):
            try:
                return dict.__getitem__(self, item)
            except KeyError:
                value = self[item] = type(self)()
                return value
    

    Testing:

    a = AutoVivification()
    
    a[1][2][3] = 4
    a[1][3][3] = 5
    a[1][2]['test'] = 6
    
    print a
    

    Output:

    {1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}
    

提交回复
热议问题