python - 如何遍历 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
}
解决方案
使用列表理解:
emails = [user["email"] for user in response["users"]]
这假设您的顶级字典存储为名为response
. 然后response["users"]
是字典列表。此列表推导循环遍历此列表,将每个用户字典分配给user
并访问其"email"
键值。
推荐阅读
- authentication - 如何配置 IBM MQ v9 以使用 Microsoft AD 进行用户认证
- c# - 如何在c#中读取列表中多个csv文件的内容
- sql - 当数据字段组合与相同和不同列匹配时选择记录
- asp.net-core - 如何让 Wix Heat.exe 保留自定义文件 ID?
- ios - setVisibleMapRect 无法预测地与 edgePadding 一起工作
- node.js - 如何修复此错误“gyp ERR!堆栈错误:EACCES:权限被拒绝,mkdir'/home/mohamedessam/Desktop/NodeJs/node_modules/bcrypt/build'”
- java - .sh 文件中应提供哪些信息
- swift - 如何在 SwiftUI 中分配可选的 Binding 参数?
- java - 重置 sqlite 序列自动增量
- mysql - 如何使下面的这个正则表达式适用于 MySql?