开发者

Python: Adding elements to an dict list or associative array

开发者 https://www.devze.com 2023-01-20 17:38 出处:网络
Im trying to add elements to a dict list (associative array), but every time it loops, the array overwrites the previous element. So i just end up with an array of size 1 with the last element read. I

Im trying to add elements to a dict list (associative array), but every time it loops, the array overwrites the previous element. So i just end up with an array of size 1 with the last element read. I verified that the keys ARE changing every tim开发者_Go百科e.

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

any help would be great, thanks =]


Your solution is incorrect; the correct version is:

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

Issues with your version:

  1. associative arrays are dicts and empty dicts = {}
  2. arrays are list , empty list = []
  3. You are pointing the array to new dictionary every time.

This is like saying:

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

array remains one element dict


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

Or:

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


Maybe even more Pythonic:

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

or, if your prog matches more groups:

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

精彩评论

暂无评论...
验证码 换一张
取 消