如何在Python中使用str作为列表索引?

时间:2016-08-29 08:30:34

标签: python

我从数据库中读取每个人的姓名和要点,我需要有类似的东西:

myarray['Alex'] = 18

我试过这个:

myArray = []
cur.execute("SELECT name, point FROM mytable WHERE name <> '' ")

for row in cur.fetchall():
    name = row[0]
    myArray[name] = row[1]

但是我收到了这个错误

TypeError: list indices must be integers, not str

1 个答案:

答案 0 :(得分:3)

您需要使用dictionary,而不是数组:

myDict = {} # Here!
cur.execute("SELECT name, point FROM mytable WHERE name <> '' ")

for row in cur.fetchall():
    name = row[0]
    myDict[name] = row[1]