2010-10-22 135 views
3

我試圖將元素添加到字典列表(關聯數組),但每次循環時,數組都會覆蓋前一個元素。所以我只是最後一個讀取最後一個元素的大小爲1的數組。我證實了鑰匙每次都在變化。Python:將元素添加到字典列表或關聯數組

array=[] 
for line in open(file): 
    result=prog.match(line) 
    array={result.group(1) : result.group(2)} 

任何幫助將是巨大的,感謝=]

回答

6

你的解決方案是不正確;正確的版本是:

array={} 
for line in open(file): 
    result=prog.match(line) 
    array[result.group(1)] = result.group(2) 

問題與您的版本:

  1. 關聯數組類型的字典和空類型的字典= {}
  2. 數組列表,空列表= []
  3. 你是每次將該數組指向新字典。

這就好比說:

array={result.group(1) : result.group(2)} 
array={'x':1} 
array={'y':1} 
array={'z':1} 
.... 

陣列保持一個元素字典

+0

非常漂亮,它的工作表示感謝。 – nubme 2010-10-22 08:03:23

+0

根據:http://diveintopython.org/getting_to_know_python/dictionaries.html 我應該能夠添加元素,我寫它的方式。我真的不明白爲什麼我不能按照網站中指定的方式進行操作。 編輯:哦,我得到了我做錯了什麼。愚蠢的我=]再次感謝 – nubme 2010-10-22 08:05:24

+0

@nubme - 不,你的方式初始化循環的每個迭代中的數組字典。參見'array = ...'初始化。 – eumiro 2010-10-22 08:07:09

0
array=[] 
for line in open(file): 
    result=prog.match(line) 
    array.append({result.group(1) : result.group(2)}) 

或者:

array={} 
for line in open(file): 
    result=prog.match(line) 
    array[result.group(1)] = result.group(2) 
+1

第一個不是OP想要的。他想要一本字典(關聯數組)。 – eumiro 2010-10-22 08:00:35

0

甚至更​​Python:

with open(filename, 'r') as f: 
    array = dict(prog.match(line).groups() for line in f) 

,或者,如果你prog匹配多個組:

with open(filename, 'r') as f: 
    array = dict(prog.match(line).groups()[:2] for line in f)