简体   繁体   中英

How to print more than one value from nested dict in Python

I am trying to parse output from Get API. My response text is:

{
 "data": [
  {
   "date_created": "22:20:47",
   "name": "test1",
   "id": "12345",
   "status": "0"
  },
  {
   "date_created": "00:09:17",
   "name": "test2",
   "id": "23456",
   "status": "0"
  },
  {
   "date_created": "00:08:02",
   "name": "test3",
   "id": "34567",
   "status": "0"
  },

I have ~100 ids. I need to print only ids and search for specific id from list.

so far, i parse with next method:

json_data = get_req.text
python_data = json.loads(json_data)
id = python_data["data"][0]["id"]
print "Object id: ", id

But it is printing only one ID, where i need all of them.

Do you have any ideas how can i print all of them?

you have a list of dicts so you need loop:

ids = [x.get('id') for x in python_data["data"]]
print (ids)

Try using this below code snippet:

for i in range(len(python_data["data"])):
    print(python_data["data"][i]["id"])

I got the expected output :

12345
23456
34567

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM