我在更新嵌套默认字典中的列表时遇到问题。
下面是我的代码:
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]})下面是输出:
{'shadyside medical building':
{'Review': [1],
'Video': [1]},
'medical building':
{'Video': [1]}}所需的输出为:
{'shadyside medical building':
{'Review': [1],
'Video': [1,1]},
'medical building':
{'Video': [1]}}请注意,视频的第二项已添加到视频列表中。
发布于 2017-01-10 22:43:20
您没有嵌套任何defaultdict,因此请执行此操作:
nested_dict = defaultdict(lambda: defaultdict(list))和
nested_dict[keyword][feature].append(pos)发布于 2019-02-14 18:48:55
您还可以创建一个无限嵌套的默认字典:
NDict = lambda: None
NDict = lambda: defaultdict(NDict)
ouroboros = NDict()
ouroboros[1][2][3][4][5][6][7][8][9] = Truehttps://stackoverflow.com/questions/41571459
复制相似问题