3 回答
TA贡献1845条经验 获得超8个赞
请尝试以下操作:
import json
with open('./source/champion.json') as json_file:
for name, info in json.load(json_file)['data'].items():
if info['key'] == 266:
print(name)
或者更好的是,我们可以在获取数据后关闭文件,而不是在处理过程中保持文件打开状态:
import json
with open('./source/champion.json') as json_file:
data = json.load(json_file)['data']
for name, info in data.items():
if info['key'] == 266:
print(name)
解释
迭代 adict的元素的最简单方法是使用它的.items()方法:
for key, value in d.items():
print(key, "-->", value)
TA贡献1725条经验 获得超7个赞
下面(仅迭代值,因为键在这里并不重要)
import json
with open('data.json') as f:
data = json.load(f)['data']
for v in data.values():
if v['key'] == '266':
print(v['name'])
break
输出
Aatrox
TA贡献1858条经验 获得超8个赞
干得好:
import json
with open('champion.json') as json_file:
data_champs = json.load(json_file)['data']
for data in data_champs.keys():
if data_champs[data]['key']=='266':
print(data_champs[data]['name'])
印刷:
Aatrox
添加回答
举报