开发者

Python: Create associative array in a loop

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'开发者_如何学Pythont the indicies must be ints.

Thanks =]

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


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


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


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)]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜