我得到了python错误TypeError:字符串索引必须是整数,而不是str
下面是我从JSON响应中得到的字典我得到了python错误TypeError:字符串索引必须是整数,而不是str,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,下面是我从JSON响应中得到的字典 {u'definitions': [{u'text': u'One venerated for experience, judgment, and wisdom.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Having or exhibiting wisdom and calm
{u'definitions': [{u'text': u'One venerated for experience, judgment, and wisdom.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Having or exhibiting wisdom and calm judgment.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Proceeding from or marked by wisdom and calm judgment: sage advice. ', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Archaic Serious; solemn.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various plants of the genus Salvia, especially S. officinalis, having aromatic grayish-green, opposite leaves. Also called ramona.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'The leaves of this plant used as a seasoning.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various similar or related plants in the mint family.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Sagebrush.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}]}
我试图使用以下代码语句访问前两个“文本”:
text1 = [body["definitions"][0]["text"],
body["definitions"][1]["text"]]
我得到了我需要的字符串
但实际的问题是,当我在我的raspberry Pi 2上运行相同的代码时,我得到以下错误
TypeError:字符串索引必须是整数,而不是str
任何帮助都将不胜感激。body[“definitions”]
返回一个字符串,请说“hello”,因此如果您写:
body["definitions"]["0"]
"hello"[0]
这相当于:
"hello"["0"]
这会产生错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
你会得到:
'h'
在raspberry PI上,您请求用户输入,而所有用户输入都是一个字符串。尝试以下操作:
data=[10,20]
,然后print(data[“0”])
它可以正常工作,如图所示,将该字典分配给正文。你确定你真的创建了一个字典,而不是仅仅尝试直接使用JSON响应(这是一个字符串,就像通过网络接收到的其他任何东西一样)?您需要显示在Pi上实际运行的实际代码,还需要准确显示如何提供数据。