What is the best way to implement nested dictionaries?

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

    As for "obnoxious try/catch blocks":

    d = {}
    d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value'
    print d
    

    yields

    {'key': {'inner key': {'inner inner key': 'value'}}}
    

    You can use this to convert from your flat dictionary format to structured format:

    fd = {('new jersey', 'mercer county', 'plumbers'): 3,
     ('new jersey', 'mercer county', 'programmers'): 81,
     ('new jersey', 'middlesex county', 'programmers'): 81,
     ('new jersey', 'middlesex county', 'salesmen'): 62,
     ('new york', 'queens county', 'plumbers'): 9,
     ('new york', 'queens county', 'salesmen'): 36}
    
    for (k1,k2,k3), v in fd.iteritems():
        d.setdefault(k1, {}).setdefault(k2, {})[k3] = v
    

提交回复
热议问题