Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Defaultdicts in Python

I'm having an issue updating a list in a nested defaultdict.

Here is my code:

a = ['20160115',    'shadyside medical building',   1, 'Review']
b = ['20160115',    'shadyside medical building',   1, 'Video']
c = ['20160215',    'shadyside medical building',   1, 'Video']
d = ['20160215',    'medical building',             1, 'Video']
f = [a,b,c,d]

nested_dict = defaultdict(dict)

for date,keyword,pos,feature in f:
    nested_dict[keyword].update({feature : [pos]})
    nested_dict[keyword].update({feature : [pos]})

Here is the output:

{'shadyside medical building': 
                             {'Review': [1], 
                             'Video': [1]}, 
'medical building': 
                   {'Video': [1]}}

The desired output is:

{'shadyside medical building': 
                             {'Review': [1], 
                             'Video': [1,1]}, 
'medical building': 
                   {'Video': [1]}}

Notice the second item for video was added to the video list.

like image 607
ethanenglish Avatar asked Sep 17 '26 19:09

ethanenglish


2 Answers

You didn’t nest any defaultdicts, so do that:

nested_dict = defaultdict(lambda: defaultdict(list))

and

nested_dict[keyword][feature].append(pos)
like image 119
Ry- Avatar answered Sep 19 '26 19:09

Ry-


You can also create an infinitely-nesting defaultdict:

NDict = lambda: None
NDict = lambda: defaultdict(NDict)

ouroboros = NDict()
ouroboros[1][2][3][4][5][6][7][8][9] = True
like image 41
emu Avatar answered Sep 19 '26 21:09

emu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!