Python nested lists / dictionaries and popping values

Sorry in advance that this was such a newbie question. I'm just starting to write python, and I got confused that you are changing values ​​from nested dictionaries / lists, so I appreciate any help!

I have json example data:

{ "scans": [ { "status": "completed", "starttime": "20150803T000000", "id":533}, { "status": "completed", "starttime": "20150803T000000", "id":539} ] } 

I would like to infer "id" from the "scan" key.

 def listscans(): response = requests.get(scansurl + "scans", headers=headers, verify=False) json_data = json.loads(response.text) print json.dumps(json_data['scans']['id'], indent=2) 

doesn't seem to work because the nested key / values ​​are inside the list. those.

 >>> print json.dumps(json_data['scans']['id']) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str 

Can someone point me in the right direction to make this work? my long-term goal is to create a for loop that puts the entire id in another dictionary or list that I can use for another function.

+5
source share
2 answers

json_data['scans'] returns a list of dicts, you are trying to index the list using str ie []["id"] , which for obvious reasons does not work, so you need to use the index to get each element:

 print json_data['scans'][0]['id'] # -> first dict print json_data['scans'][1]['id'] # -> second dict 

Or, to see all iterations of the identifier over the list of returned dicts using json_data["scans"] :

 for dct in json_data["scans"]: print(dct["id"]) 

To save adding to the list:

 all_ids = [] for dct in json_data["scans"]: all_ids.append(dct["id"]) 

Or use the comp list:

 all_ids = [dct["id"] for dct in json_data["scans"]] 

If there is a possibility that the id key may not be present in each dict, use in to check before access:

 all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct] 
+2
source

Here you can iterate over elements and retrieve all identifiers:

 json_data = ... ids = [] for scan in json_data['scans']: id = scan.pop('id') # you can use get instead of pop # then your initial data would not be changed, # but you'll still have the ids # id = scan.get('id') ids.append(); 

This approach will also work:

 ids = [item.pop('id') for item in json_data['scans']] 
0
source

All Articles