簡體   English   中英

從python中的字典列表創建列表的問題

[英]Issues creating list from list of dictionaries in python

我有一個包含 json 數據的文件,如下所示:

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"
                    ]
                }
            }
        ]

我設法使用以下代碼提取了“first_name”值以及“primary_email”

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)

產生以下輸出:

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

然而,我正在努力為姓名和電子郵件創建兩個單獨的列表,如下所示:

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

非常感謝您對此的任何幫助。

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)

或在同一個循環中:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM