1
我正在尝试构建字典,其中每个键都有一个字典本身的值。 与下面的代码,它不追加新项目新时,如果完成Python中循环字典词典
dict_features = {}
def regexp_features(fileids):
for fileid in fileids:
if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)):
dict_features[fileid] = {'oskorblenie':'1'}
else:
dict_features[fileid] = {'oskorblenie':'0'}
if re.search(r'честны*|труд*', agit_corpus.raw(fileid)):
dict_features[fileid] = {'samoprezentacia':'1'}
else:
dict_features[fileid] = {'samoprezentacia':'0'}
return dict_features
结果字典中的问题是字典
{'neagitacia/20124211.txt': {'samoprezentacia': '0'}, 'agitacia/discreditacia1.txt': {'samoprezentacia': '0'}
但我需要
{'neagitacia/20124211.txt': {'oskorblenie':'1', 'samoprezentacia': '0'}, 'agitacia/discreditacia1.txt': {'oskorblenie':'0', 'samoprezentacia': '0'}
谢谢!我已经尝试过dict_features [fileid] ['oskorblenie'] ='1',但没有默认字典它产生了KeyError。现在它可以工作。 –
@VicNicethemer:这是defaultdicts的工作方式,对于不存在的键,它们给键赋予默认值,使用它可以将东西分配给它。很高兴我的回答很有帮助。 :) –