3 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
請(qǐng)嘗試以下操作:
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)
或者更好的是,我們可以在獲取數(shù)據(jù)后關(guān)閉文件,而不是在處理過程中保持文件打開狀態(tài):
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的元素的最簡(jiǎn)單方法是使用它的.items()方法:
for key, value in d.items():
print(key, "-->", value)

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面(僅迭代值,因?yàn)殒I在這里并不重要)
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貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
干得好:
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
添加回答
舉報(bào)