Python: Append Multiple Values for One Key in Nested Dictionary
Question: I have the below list of tuples:

    
    
    p = [("01","Master"),("02","Node"),("03","Node"),("04","Server")]
    

I want my output to look like:

    
    
    y = {
         "Master":{"number":["01"]},
         "Node":{"number":["02", "03"]},
         "Server":{"number":["04"]}
         }
    

I have tried the below code:

    
    
    y = {}
    for line in p:
         if line[1] in y:
              y[line[1]] = {}
              y[line[1]]["number"].append(line[0])
         else:
              y[line[1]] = {}
              y[line[1]]["number"] = [line[0]]
    

And I get the below error:

    
    
     Traceback (most recent call last):
             File "<stdin>", line 4, in <module>
     KeyError: 'number'
    

How do I solve this?


Answer: 
    from collections import defaultdict
    
    d = defaultdict(lambda: defaultdict(list))
    for v, k in p:
        d[k]["number"].append(v)
    
    
    print(d)
    
      defaultdict(<function <lambda> at 0x7f8005097578>, {'Node': defaultdict(<type 'list'>, {'number': ['02', '03']}), 'Master': defaultdict(<type 'list'>, {'number': ['01']}), 'Server': defaultdict(<type 'list'>, {'number': ['04']})})
    

without defaultdict:

    
    
    d = {}
    from pprint import pprint as pp
    for v, k in p:
        d.setdefault(k,{"number":[]})
        d[k]["number"].append(v)
    
    
    pp(d)
    
    {'Master': {'number': ['01']},
     'Node': {'number': ['02', '03']},
     'Server': {'number': ['04']}}
    

