What is the best way to implement nested dictionaries?

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

    If the number of nesting levels is small, I use collections.defaultdict for this:

    from collections import defaultdict
    
    def nested_dict_factory(): 
      return defaultdict(int)
    def nested_dict_factory2(): 
      return defaultdict(nested_dict_factory)
    db = defaultdict(nested_dict_factory2)
    
    db['new jersey']['mercer county']['plumbers'] = 3
    db['new jersey']['mercer county']['programmers'] = 81
    

    Using defaultdict like this avoids a lot of messy setdefault(), get(), etc.

提交回复
热议问题