Python从嵌套字典中取值:
字典形式:
content = {'code':1, 'message':'获取成功','result':'Answer','data':{'answer':{'id':123,'name':'张三','class':'二年级'}}}
content1 = {'code':1, 'message':'获取成功','result':'Smianswer','data':{'smianswer':[{'id':123,'name':'张三','class':'二年级'},{'id':234,'name':'李四','class':'三年级'},{'id':345,'name':'王五','class':'四年级'}]}}
content = {'code':1, 'message':'获取成功','result':'Answer','data':{'answer':{'id':123,'name':'张三','class':'二年级'}}}
result = content['data']
print(result)
print()
result = content['data']['answer']
print(result)
print()
result = content['data']['answer']['name']
print(result)
print()
result = content['data']['answer']['id']
print(result)
print("*"*40)
content1 = {'code':1, 'message':'获取成功','result':'Smianswer','data':{'smianswer':[{'id':123,'name':'张三','class':'二年级'},{'id':234,'name':'李四','class':'三年级'},{'id':345,'name':'王五','class':'四年级'}]}}
result = content1['data']
print(result)
print()
#取出集合
result = content1['data']['smianswer']
print(result)
print()
#遍历集合,拿出自己想要的内容
names = []
for i in result:
(i['name'])
print(names)
打印结果:
{'answer': {'id': 123, 'name': '张三', 'class': '二年级'}}
{'id': 123, 'name': '张三', 'class': '二年级'}
张三
123
****************************************
{'smianswer': [{'id': 123, 'name': '张三', 'class': '二年级'}, {'id': 234, 'name': '李四', 'class': '三年级'}, {'id': 345, 'name': '王五', 'class': '四年级'}]}
[{'id': 123, 'name': '张三', 'class': '二年级'}, {'id': 234, 'name': '李四', 'class': '三年级'}, {'id': 345, 'name': '王五', 'class': '四年级'}]
['张三', '李四', '王五']
Process finished with exit code 0