python - 在 Python 字典中访问同级字典值的最有效方法是什么?

标签 python loops dictionary list-comprehension

在 Python 中,我有一个看起来像这样的字典列表:

matchings = [
    {'id': 'someid1', 'domain': 'somedomain1.com'},
    {'id': 'someid2', 'domain': 'somedomain2.com'},
    {'id': 'someid3', 'domain': 'somedomain3.com'}
]

而且,我有一个变量:

the_id = 'someid3'

检索项目域值的最有效方法是什么?

最佳答案

您可以使用 list comprehension :

domains = [matching['domain'] for matching in matchings if matching['id'] == the_id]

遵循格式标准格式:

resulting_list = [item_to_return for item in items if condition]

并且基本上封装了以下所有功能:

domains = []
for matching in matchings:
    if matching['id'] == the_id:
        domains.append(matching['domain'])

所有这些功能都使用列表理解在一行中表示。

关于python - 在 Python 字典中访问同级字典值的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/451690/

相关文章:

python - 如何在 Python 中初始化空列表字典?

python - 如何从数据框中删除\n并将数据移动到新行

Python PIL 减少字母间距

python - 如何只允许更新1个字段?

r - 在 r 中为多个箱形图创建循环

python - 如何以必须从同一字符串中提取键和值的方式将字符串转换为字典

dictionary - 为什么 map 中没有键

python - 在特定目录的上下文中运行 python unittest

php - 在循环中创建 HTML 元素

ios - 无法通过 Swift 中的计数器循环