What is the best way to implement nested dictionaries?

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

    You can use recursion in lambdas and defaultdict, no need to define names:

    a = defaultdict((lambda f: f(f))(lambda g: lambda:defaultdict(g(g))))
    

    Here's an example:

    >>> a['new jersey']['mercer county']['plumbers']=3
    >>> a['new jersey']['middlesex county']['programmers']=81
    >>> a['new jersey']['mercer county']['programmers']=81
    >>> a['new jersey']['middlesex county']['salesmen']=62
    >>> a
    defaultdict(>,
            {'new jersey': defaultdict(>,
                         {'mercer county': defaultdict(>,
                                      {'plumbers': 3, 'programmers': 81}),
                          'middlesex county': defaultdict(>,
                                      {'programmers': 81, 'salesmen': 62})})})
    

提交回复
热议问题