2013-08-02 3 views
1

각 키는 사전 자체의 값을 가진 사전을 만들려고합니다. 이사전의 사전에있는 파이썬

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 

결과를 수행하는 경우 때 새 사전에 새 항목을 추가하지 않습니다 다음 코드의 문제는 DICT

{'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에 대한 값을 다시 써야합니다. 하나 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'} 

, 당신은 첫 번째를 만든 다음 두 번째 if-else 구조를 사용하여 교체하십시오. 당신은 무엇을 찾고있을 수 있습니다 것이 기본 값으로 dictdefaultdict입니다

(중 하나 if 또는 else 항상 실행되기 때문에 모두 if-else 구조 값을 넣어). 의 라인을 따라 뭔가 -

>>> 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가 작동하는 방식입니다. 존재하지 않는 키의 경우 키에 기본값을 지정하고,이를 사용하여 항목을 할당 할 수 있습니다. 다행 인 것은 다행이었습니다. :) –

관련 문제