我在嵌套的defaultdict中更新列表时遇到问题.
这是我的代码:
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]}}
请注意,视频的第二项已添加到视频列表中.
你没有嵌套任何defaultdict
s,所以这样做:
nested_dict = defaultdict(lambda: defaultdict(list))
和
nested_dict[keyword][feature].append(pos)