Apologies in advance for this being such a newbie question. I'm just beginning to write python and i've been having some confusion around popping values from nested dictionaries/lists so i appreciate any help!
I have this sample json data:
{ "scans": [
{ "status": "completed", "starttime": "20150803T000000", "id":533},
{ "status": "completed", "starttime": "20150803T000000", "id":539}
] }
i'd like to pop the 'id' out of the "scans" 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)
doesnt seem to be working because the nested key/values are inside of a list. i.e.
>>> 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 anyone point me in the right direction to get this to work? my longterm goal with this is to create a for-loop that places all of the id's into another dictionary or list that i can use for another function.
Deleting dictionaries from a Nested Dictionary Deletion of dictionaries from a nested dictionary can be done either by using del keyword or by using pop() function.
To add new values to the end of the nested list, use append() method. When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method. If you know the index of the item you want, you can use pop() method.
A Python list can contain a dictionary as a list item.
A dictionary can contain dictionaries, this is called nested dictionaries.
json_data['scans']
returns a list of dicts, you are trying to index the list using a str i.e []["id"]
which fails for obvious reasons so you need to use the index to get each subelement:
print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict
Or to see all the id's iterate over the list of dicts returned using json_data["scans"]
:
for dct in json_data["scans"]:
print(dct["id"])
To save append to a list:
all_ids = []
for dct in json_data["scans"]:
all_ids.append(dct["id"])
Or use a list comp:
all_ids = [dct["id"] for dct in json_data["scans"]]
If there is a chance the key id
might not be in every dict, use in
to check before you access:
all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With