Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python nested lists/dictionaries and popping values

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.

like image 465
dobbs Avatar asked Aug 03 '15 15:08

dobbs


People also ask

How do you pop a nested dictionary in Python?

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.

How do you pop an element in a nested list?

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.

Can you nest a dictionary in a list Python?

A Python list can contain a dictionary as a list item.

Can dictionaries be nested?

A dictionary can contain dictionaries, this is called nested dictionaries.


1 Answers

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]
like image 129
Padraic Cunningham Avatar answered Sep 23 '22 16:09

Padraic Cunningham