What is the best way to implement nested dictionaries?

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

    defaultdict() is your friend!

    For a two dimensional dictionary you can do:

    d = defaultdict(defaultdict)
    d[1][2] = 3
    

    For more dimensions you can:

    d = defaultdict(lambda :defaultdict(defaultdict))
    d[1][2][3] = 4
    

提交回复
热议问题