类型错误:字符串索引必须是整数(Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49695836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: string indices must be integers (Python)
提问by Martin
I am trying to retrieve the 'id' value : ad284hdnn.
我正在尝试检索“id”值:ad284hdnn。
I am getting the following error : TypeError: string indices must be integers
我收到以下错误: TypeError: string indices must be integers
data = response.json()
print data
for key in data['result']:
print key['id']
Here is the json that is returned when print the data string.
这是打印数据字符串时返回的json。
{u'meta': {u'httpStatus': u'200 - OK', u'requestId': u'12345'}, u'result': {u'username': u'[email protected]', u'firstName': u'joe', u'lastName': u'bloggs', u'accountStatus': u'active', u'id': u'ad284hdnn'}}
回答by radzak
data['result']
is a dictionary. Iterating over dict
means iterating over its keys. Therefore key
variable stores a string. That's why key['id']
raises TypeError: string indices must be integers
.
data['result']
是字典。迭代dict
意味着迭代它的键。因此key
变量存储一个字符串。这就是为什么key['id']
提出TypeError: string indices must be integers
.