首页 > 解决方案 > 如何遍历 python DICT 以提取特定键的特定值?

问题描述

我有下面显示的以下字典,它是从 GET 请求创建的。我想遍历这个字典以仅提取所有用户电子邮件。我不想要带有值的键,只是一个新的电子邮件地址列表。我怎样才能最有效地遍历一个长字典并只提取键“电子邮件”的值?我曾尝试使用 json.load() 函数,但遇到了数据类型的问题。

{
    "users": [
        {
            "id": 1262635064750,
            "url": "https://xxxx.xxx.com/api/v2/users/1262635064xxx.json",
            "name": "Customer A",
            "email": "customerA@example.com",
            "created_at": "2021-03-05T22:05:12Z",
            "updated_at": "2021-03-05T22:05:15Z",
            "time_zone": "America/Chicago",
            "iana_time_zone": "America/Chicago",
            "phone": null,
            "shared_phone_number": null
         }
 {
            "id": 1262635064751,
            "url": "https://xxxx.xxx.com/api/v2/users/1262635064xxx.json",
            "name": "Customer B",
            "email": "customerB@example.com",
            "created_at": "2021-03-05T22:05:12Z",
            "updated_at": "2021-03-05T22:05:15Z",
            "time_zone": "America/Chicago",
            "iana_time_zone": "America/Chicago",
            "phone": null,
            "shared_phone_number": null
         }
 {
            "id": 1262635064752A,
            "url": "https://xxxx.xxx.com/api/v2/users/1262635064xxx.json",
            "name": "Customer C",
            "email": "customerC@example.com",
            "created_at": "2021-03-05T22:05:12Z",
            "updated_at": "2021-03-05T22:05:15Z",
            "time_zone": "America/Chicago",
            "iana_time_zone": "America/Chicago",
            "phone": null,
            "shared_phone_number": null
         }

标签: python

解决方案


使用列表理解

emails = [user["email"] for user in response["users"]]

这假设您的顶级字典存储为名为response. 然后response["users"]是字典列表。此列表推导循环遍历此列表,将每个用户字典分配给user并访问其"email"键值。


推荐阅读