2016-01-22 44 views
0

我有,看起來像檢索鍵,JSON數據蟒蛇的價值

{"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007} 

我試圖環雖然字典並打印其相應價值的關鍵,在我的代碼字典的JSON文件獲得太多值來解開錯誤。

with open('myfile.json', "r") as myfile: 
json_data = json.load(myfile) 
for e, v in json_data: 
    for key, value in e.iteritem(): 
    print key, value 

回答

1

因此,默認情況下,dict將迭代其密鑰。

for key in json_data: 
    print key 
# tvs, sofas, etc... 

相反,它似乎是你想迭代的鍵值對。這可以通過在字典上調用.items()來完成。

for key, value in json_data.items(): 
    print key, value 

或者您也可以通過調用.values()遍歷剛剛值。

1

這是你要找的嗎?

>>> json = {"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007} 
>>> for j in json: 
...  print j, json[j] 
... 
chairs 27 
sofas 31 
cpus 7 
tvs 92 
1

試試這個:

with open('myfile.json', "r") as myfile: 
    json_data = json.load(myfile) 
    for e, v in json_data.items(): 
     print e,v 

你在你的代碼有一個額外的循環,此外,輸入文件具有無效數據007。加載到json應該會給你一個錯誤。