2016-01-22 69 views
0

我有一本字典一個JSON文件,並列出了字典獲得的Json詞典/列表值蟒蛇

{"Dogs": [["spot"], 1], "Cats": [["whiskers"], 1], "fish": [["bubbles", "lefty", "tank", "goldie"], 4], "elephant": [["tiny", "spring"], 2], "zebra": [[], 1], "gazelle": [["red", "blue", "green", "yellow", "gold", "silver"], 6]} 

還有更多的字典裏面,但是從這個例子可以看到的格式。

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

這給了我

too many values to unpack error. 

我想輸出看起來像

dogs spot 1 
cats whiskers 1 
+0

你有什麼要發生的魚嗎?你無法解壓縮到列表中。 – L3viathan

+0

列表中有多個東西時應該輸出什麼內容? –

回答

1

假設你希望所有動物的名字(?)輸出

... 
for e, (v, z) in json_data.items(): 
    print('%s %s %d' % (e.lower(), ' '.join(v), z)) 

輸出

gazelle red blue green yellow gold silver 6 
fish bubbles lefty tank goldie 4 
cats whiskers 1 
zebra 1 
elephant tiny spring 2 
dogs spot 1 
0

簡單得多,因爲值總是將是一個列表:

with open('myfile.json', 'r') as myfile:  
    json_data = json.load(t) 
    for e, v in json_data.items(): 
     print e, " ".join(v[0]), v[1] 

這給:

gazelle red blue green yellow gold silver 6 
fish bubbles lefty tank goldie 4 
Cats whiskers 1 
zebra 1 
elephant tiny spring 2 
Dogs spot 1