简体   繁体   中英

How to use str as list index in Python?

I read the name and the points of each person from a database and I need to have something like that:

myarray['Alex'] = 18

I've tried this :

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

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

but I got this error

TypeError: list indices must be integers, not str

You need to use a dictionary , not an array:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM