TypeError-字符串索引必须是整数,而不是s

2024-05-21 04:13:01 发布

您现在位置:Python中文网/ 问答频道 /正文

当我打印从MongoDB检索到的数据时,得到了以下输出:

[{"username": "ashish.mishra", "password": "hxMNwFOa", "frequency": "Daily", "name": "Ashish Mishra", "email": "ashish@mail.com"}]

我是这样找回的:

user = db.UserData.find()
user = dumps(user)
print user //this is the printed version above

我想拿到每把钥匙。我试过:

print user['username']

以及

print user[0]['username']

它给了我错误:

TypeError: string indices must be integers, not str

我知道这上面有很多线索,但到目前为止我还没有成功。知道怎么做吗?


Tags: 数据nameemailmongodbusernamepassworddailyprint
2条回答

列表对象中有字典对象。

这里的问题是,Python假设您想要使用提供的索引号从列表中检索一个项。

从users变量中移除括号,您的字典将成为字典。

users = {"username": "ashish.mishra", "password": "hxMNwFOa", "frequency": "Daily", "name": "Ashish Mishra", "email": "ashish@mail.com"}
print user['username']

必须先将字符串转换为字典,如下所示:

import json

# initialize user here
user_dict = json.loads(user)
print user_dict[0]['username']

相关问题 更多 >