views:

80

answers:

3

I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints.

Thanks =]

for line in open(file):
  x=prog.match(line)
  myarray[x.group(1)]=[x.group(2)]
A: 

Because array indices should be an integer

>>> a = [1,2,3]
>>> a['r'] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> a[1] = 4
>>> a
[1, 4, 3]

x.group(1) should be an integer or

if you are using map define the map first

myarray = {}
for line in open(file):
  x=prog.match(line)
  myarray[x.group(1)]=[x.group(2)]
pyfunc
but i want an associative array, aka hash table, or mapping
nubme
@nubme: got it and edited my reply
pyfunc
+4  A: 

Associative arrays in Python are called mappings. The most common type is the dictionary.

Ignacio Vazquez-Abrams
Thanks ignacio, but how would i add it via loop if i dont know all the values ahead of time.
nubme
Start with an empty dictionary.
Ignacio Vazquez-Abrams
nm got it. thanks =]
nubme
+2  A: 
myarray = {} # Declares myarray as a dict
for line in open(file, 'r'):
    x = prog.match(line)
    myarray[x.group(1)] = [x.group(2)] # Adds a key-value pair to the dict
Sancho