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