简体   繁体   English

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

[英]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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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