简体   繁体   中英

Issues creating list from list of dictionaries in python

I have a file with json data in it like this:

data = [
            {
                "id": 12345678,
                "list_id": 12345,
                "creator_id": 1234567,
                "entity_id": 1234567,
                "created_at": "2020-01-30T00:43:55.256-08:00",
                "entity": {
                    "id": 123456,
                    "type": 0,
                    "first_name": "John",
                    "last_name": "Doe",
                    "primary_email": "john@fakemail.com",
                    "emails": [
                        "john@fakemail.com"
                    ]
                }
            },
            {
                "id": 12345678,
                "list_id": 12345,
                "creator_id": 1234567,
                "entity_id": 1234567,
                "created_at": "2020-01-30T00:41:54.375-08:00",
                "entity": {
                    "id": 123456,
                    "type": 0,
                    "first_name": "Jane",
                    "last_name": "Doe",
                    "primary_email": "jane@fakemail.com",
                    "emails": [
                        "jane@fakemail.com"
                    ]
                }
            }
        ]

I managed to extract the "first_name" values as well as the "primary_email" with the following code

for record in data:
    first_names = record.get('entity',{}).get('first_name', None)
    email = record.get('entity',{}).get('primary_email', None)
    print(first_names)
    print(email)

which produces following output:

John
john@fakemail.com
Jane
jane@fakemail.com

I am struggling however to create two separate lists for names and email like this:

(John,Jane)
(john@fakemail.com,jane@fakemail.com)

Any help with this is much appreciated.

import json


first_names = [record.get('entity',{}).get('first_name', None) for record in data]
email = [record.get('entity',{}).get('primary_email', None) for record in data]
print(first_names)
print(email)

or in the same loop:

first_names = []
email = []
for record in data:
    first_names.append(record.get('entity',{}).get('first_name', None))
    email.append(record.get('entity',{}).get('primary_email', None))
print(first_names)
print(email)

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