2010-10-22 112 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)