Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading