pythondictionarydefaultdict

Use of defalut dict such that the default is a dict with an empty list


The main object is a dictionary whose keys are strings, values a 2nd dictionary.
The 2nd dictionary has string keys, and list values.

I want to append a new value to the empty list created using defalutdict()

Here is what I am trying to do:

import collections
my_dict = collections.defaultdict(dict,{'missing_key': [] } )
my_dict['foo']['bar'].append('1')

And the result produced by Idle u3.10.11:

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    my_dict['foo']['bar'].append('1')
KeyError: 'bar'

Solution

  • The first parameter of the defaultdict is the default value on missing keys. So if you want two layers of defaulting, you use two layers of defaultdicts:

    from collections import defaultdict
    my_dict = defaultdict(lambda: defaultdict(list))
    my_dict['foo']['bar'].append('1')
    

    my_dict['foo'] -> key missing -> calls lambda -> inserts a defaultdict(list) ->

    my_dict = defaultdict(..., {
        'foo': defaultdict(list),
    })
    

    ['bar'] -> key missing -> calls list -> inserts an empty list

    my_dict = defaultdict(..., {
        'foo': defaultdict(list, {'bar': []}),
    })
    

    and then you append(1) into that