2016-01-22 67 views
6

我在它與JSON數據的文件,像這樣:在Python中迭代JSON列表的問題?

{ 
    "Results": [ 
      {"Id": "001", 
      "Name": "Bob", 
      "Items": { 
       "Cars": "1", 
       "Books": "3", 
       "Phones": "1"} 
      }, 

      {"Id": "002", 
      "Name": "Tom", 
      "Items": { 
       "Cars": "1", 
       "Books": "3", 
       "Phones": "1"} 
      }, 

      {"Id": "003", 
      "Name": "Sally", 
      "Items": { 
       "Cars": "1", 
       "Books": "3", 
       "Phones": "1"} 
      }] 
} 

我無法弄清楚如何通過JSON正常循環。我想循環訪問數據,併爲數據集中的每個成員獲取一個帶汽車的名稱。我怎樣才能做到這一點?

import json 

with open('data.json') as data_file: 
    data = json.load(data_file) 

print data["Results"][0]["Name"] # Gives me a name for the first entry 
print data["Results"][0]["Items"]["Cars"] # Gives me the number of cars for the first entry 

我試圖通過他們與循環:

for i in data["Results"]: 
print data["Results"][i]["Name"]  

但收到一個錯誤: 類型錯誤:列表索引必須是整數,而不是字典

+1

'爲i的數據[「結果」]:I [「名稱「]' –

+1

如果我正確理解了你的話,你需要:'[person''Name']:person ['Items'] ['Cars'] for data in data [」Results「]}'。 – pzp

回答

13

你假設i是索引,但它是一本詞典,用途:

for item in data["Results"]: 
    print item["Name"]  
0從

報價:

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

+0

現在有道理,謝謝你的快速回復! 我仍然不確定如何通過每個子對象循環? – Bajan

+2

@Bajan當然,假設你的意思是'Items'字典:'對於項目[「Items」中的鍵值)。iteritems():'。請參閱相關主題:https://docs.python.org/2/tutorial/datastructures.html#dictionaries,http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-在-蟒蛇。 – alecxe

+1

你很快! 我通過使用這個來完成: '對於數據中的項目[「結果」]:打印項目[「項目」] [「汽車」]' 這將是推薦的方法? – Bajan

3

您翻翻字典,迭代不索引,所以你要麼使用。

for item in data["Results"]: 
    print item["Name"]  

for i in range(len(data["Results"])): 
    print data["Results"][i]["Name"] 
2

的混亂是在如何字典和列表中迭代中使用。 字典會遍歷它的鍵(您使用的指數來獲得相應的值)

x = {"a":3, "b":4, "c":5} 
for key in x: #same thing as using x.keys() 
    print(key,x[key]) 

for value in x.values(): 
    print(value)  #this is better if the keys are irrelevant  

for key,value in x.items(): #this gives you both 
    print(key,value) 

但迭代一個列表的默認行爲會給你的元素,而不是指數:

y = [1,2,3,4] 
for i in range(len(y)): #iterate over the indices 
    print(i,y[i]) 

for item in y: 
    print(item) #doesn't keep track of indices 

for i,item in enumerate(y): #this gives you both 
    print(i,item) 

如果你想推廣你的程序,你可以使用這些功能一個同樣的方式來處理兩種類型:

def indices(obj): 
    if isinstance(obj,dict): 
     return obj.keys() 
    elif isinstance(obj,list): 
     return range(len(obj)) 
    else: 
     raise TypeError("expected dict or list, got %r"%type(obj)) 

def values(obj): 
    if isinstance(obj,dict): 
     return obj.values() 
    elif isinstance(obj,list): 
     return obj 
    else: 
     raise TypeError("expected dict or list, got %r"%type(obj)) 

def enum(obj): 
    if isinstance(obj,dict): 
     return obj.items() 
    elif isinstance(obj,list): 
     return enumerate(obj) 
    else: 
     raise TypeError("expected dict or list, got %r"%type(obj)) 

這樣,如果你對例如,以後改變了JSON來存儲使用id作爲鍵,則該程序仍然遍歷它以同樣的方式在一個字典的結果:

#data = <LOAD JSON> 
for item in values(data["Results"]): 
    print(item["name"]) 

#or 
for i in indices(data["Results"]): 
    print(data["Results"][i]["name"])