Problems repeating through JSON list in Python?

I have a file with JSON data in it, for example:

{ "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"} }] } 

I can't figure out how to properly scroll through JSON. I would like to view the data and get a name with the authors for each member in the data set. How can i do this?

 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 

I tried them through:

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

But get the error: TypeError: list indices must be integers, not dict

+6
source share
3 answers

You assume i is an index, but this is a dictionary, use:

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

Quote from for statements :

The for statement in Python is slightly different from what you can use in C or Pascal. Instead of always repeating the arithmetic progression of numbers (for example, in Pascal) or giving the user the ability to determine both the iteration step and the stop condition (like C), the Pythons operator to iterate over elements of any sequence (list or line), in the order they are occurrences in sequence.

+13
source

you iterate through a dictionary, not indexes, so you should either use.

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

or

 for i in range(len(data["Results"])): print data["Results"][i]["Name"] 
+3
source

The confusion is how dictionaries and lists are used in iteration. The dictionary will iterate over the keys through it (which you use as indexes to get the corresponding values)

 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) 

but the default iteration behavior by default will give you elements instead of indexes:

 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) 

If you want to generalize your program to handle both types the same way you could use one of the following functions:

 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)) 

Thus, if, for example, you later changed json to save the results in a dict, using id as keys, the program will iterate over it the same way:

 #data = <LOAD JSON> for item in values(data["Results"]): print(item["name"]) #or for i in indices(data["Results"]): print(data["Results"][i]["name"]) 
+2
source

All Articles