x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
y = json.dumps(x)
z = json.loads(y)
for i in z:
if i["owner"] == "bob":
print(i['petname'])
break
此代码的目标是在提供所有者姓名的同时返回宠物名称。例如,通过赋予所有者名称“bob”来输出“fido”
但是我得到的只是TypeError: string indices must be integers
. 我究竟做错了什么?谢谢
您正在迭代基础dictionary
而不是迭代list
下people
迭代z["people"]
其中包含一个list
,而不是迭代z
解决方案
x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
y = json.dumps(x)
z = json.loads(y)
for i in z["people"]:
if i["owner"] == "bob":
print(i['petname'])
break
另外,我认为没有必要使用
y = json.dumps(x)
z = json.loads(y)
您可以简单地使用基本字典 x
for i in x["people"]:
if i["owner"] == "bob":
print(i['petname'])
break
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句