Python: Adding elements to an dict list or associative array

11,937

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

Share:
11,937

Related videos on Youtube

nubme
Author by

nubme

Updated on May 06, 2022

Comments

  • nubme
    nubme almost 2 years

    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 time.

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

    any help would be great, thanks =]

  • nubme
    nubme over 13 years
    according to: diveintopython.org/getting_to_know_python/dictionaries.html i should be able to add elements the way i wrote it. i dont really get why i couldnt do it the way specified in the site. EDIT: oh i get what i was doing wrong. stupid me =] thanks again
  • eumiro
    eumiro over 13 years
    @nubme - no, your way initializes the array dictionary in each iteration of the loop. See the array = ... initialization.
  • pyfunc
    pyfunc over 13 years
    @nubme: See my last part of answer. It is like saying k =1 then k=2 then k=3. K would be 3 right. and not 1, 2, 3. In the loop, you are pointing array to new dict each time.
  • mripard
    mripard over 13 years
    The way you do it, you instanciate a new dict object and replace the previous one. The {foo: bar} syntax is ok when you create the object. When you want to add an element to a dict, you have to use dict[foo] = bar.