2013-08-02 174 views
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'} 

回答

1

你是重写相同的值fileid

在你的代码,

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'} 

对于一个fileid,您创建的第一个,然后用第二if-else结构取代它。 (无论是if-else构建放值,因为无论是ifelse就一定会执行)

你可能会寻找一个defaultdictdict作为默认值。沿着线的东西 -

>>> from collections import defaultdict 
>>> a = defaultdict(dict) 
>>> a['abc'] 
{} 
>>> a['abc']['def'] = 1 
>>> a 
defaultdict(<type 'dict'>, {'abc': {'def': 1}}) 
>>> a['abc']['fgh'] = 2 
>>> a 
defaultdict(<type 'dict'>, {'abc': {'fgh': 2, 'def': 1}}) 

所以,你的代码可能会更改为

dict_features = defaultdict(dict) 
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 
+0

谢谢!我已经尝试过dict_features [fileid] ['oskorblenie'] ='1',但没有默认字典它产生了KeyError。现在它可以工作。 –

+0

@VicNicethemer:这是defaultdicts的工作方式,对于不存在的键,它们给键赋予默认值,使用它可以将东西分配给它。很高兴我的回答很有帮助。 :) –