response={'reason': 'success!',
'result': [{'province_id': '1', 'province': '安徽', 'citys': [{'city_id': '10001', 'city': '合肥'},
{'city_id': '10002', 'city': '芜湖'},
{'city_id': '10003', 'city': '蚌埠'},
{'city_id': '10004', 'city': '淮南'},
{'city_id': '10005', 'city': '马鞍山'},
{'city_id': '10006', 'city': '淮北'},
{'city_id': '10007', 'city': '铜陵'},
{'city_id': '10008', 'city': '安庆'},
{'city_id': '10009', 'city': '黄山'},
{'city_id': '10010', 'city': '滁州'}]},
{'province_id': '2', 'province': '北京', 'citys': [{'city_id': '10017', 'city': '北京'}]},
{'province_id': '3', 'province': '重庆', 'citys': [{'city_id': '10018', 'city': '重庆'}]}],
'error_code': 0}
1、获取response字典中键和值
for key, values in response.items():
print(key,values)
结果:
reason success!
result [{'province_id': '1', 'province': '安徽', 'citys': [{'city_id': '10001', 'city': '合肥'}, {'city_id': '10002', 'city': '芜湖'}, {'city_id': '10003', 'city': '蚌埠'}, {'city_id': '10004', 'city': '淮南'}, {'city_id': '10005', 'city': '马鞍山'}, {'city_id': '10006', 'city': '淮北'}, {'city_id': '10007', 'city': '铜陵'}, {'city_id': '10008', 'city': '安庆'}, {'city_id': '10009', 'city': '黄山'}, {'city_id': '10010', 'city': '滁州'}]}, {'province_id': '2', 'province': '北京', 'citys': [{'city_id': '10017', 'city': '北京'}]}, {'province_id': '3', 'province': '重庆', 'citys': [{'city_id': '10018', 'city': '重庆'}]}]
error_code 0
2、取“result”的值(取字典的值,Name['键名'])
print(response['result'])
结果:
[{'province_id': '1', 'province': '安徽', 'citys': [{'city_id': '10001', 'city': '合肥'}, {'city_id': '10002', 'city': '芜湖'}, {'city_id': '10003', 'city': '蚌埠'}, {'city_id': '10004', 'city': '淮南'}, {'city_id': '10005', 'city': '马鞍山'}, {'city_id': '10006', 'city': '淮北'}, {'city_id': '10007', 'city': '铜陵'}, {'city_id': '10008', 'city': '安庆'}, {'city_id': '10009', 'city': '黄山'}, {'city_id': '10010', 'city': '滁州'}]}, {'province_id': '2', 'province': '北京', 'citys': [{'city_id': '10017', 'city': '北京'}]}, {'province_id': '3', 'province': '重庆', 'citys': [{'city_id': '10018', 'city': '重庆'}]}]
3、获取“result”列表里全部字典的键和值(获取字典列表里的值)
for i in response['result']:
for key,values in i.items():
print(key,values)
结果:
province_id 1
province 安徽
citys [{'city_id': '10001', 'city': '合肥'}, {'city_id': '10002', 'city': '芜湖'}, {'city_id': '10003', 'city': '蚌埠'}, {'city_id': '10004', 'city': '淮南'}, {'city_id': '10005', 'city': '马鞍山'}, {'city_id': '10006', 'city': '淮北'}, {'city_id': '10007', 'city': '铜陵'}, {'city_id': '10008', 'city': '安庆'}, {'city_id': '10009', 'city': '黄山'}, {'city_id': '10010', 'city': '滁州'}]
province_id 2
province 北京
citys [{'city_id': '10017', 'city': '北京'}]
province_id 3
province 重庆
citys [{'city_id': '10018', 'city': '重庆'}]
4、获取所有province_id的值
list=response['result']
for i in list:
print(i['province_id'])
结果:
1
2
3
5、获取所有“city_id”的值
list=response['result']
for i in list:
for id in i['citys']:
print(id['city_id'])
结果:
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10017
10018