Python:向dict列表或关联数组添加元素

时间:2010-10-22 07:54:52

标签: python list associative-array

我试图将元素添加到字典列表(关联数组),但每次循环时,数组都会覆盖前一个元素。所以我最终得到一个大小为1的数组,最后一个元素被读取。我确认钥匙每次都在变化。

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

任何帮助都会很棒,谢谢=]

3 个答案:

答案 0 :(得分:6)

您的解决方案不正确;正确的版本是:

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

您的版本问题:

  1. 关联数组是dicts,空dicts = {}
  2. 数组是列表,空列表= []
  3. 您每次都将数组指向新词典。
  4. 这就像说:

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

    数组仍然是一个元素dict

答案 1 :(得分: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)

答案 2 :(得分:0)

也许更多Pythonic:

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)