【问题标题】:Python - How to deal with missing keys while iterating through a list of dictionaries? [duplicate]Python - 如何在遍历字典列表时处理丢失的键? [复制]
【发布时间】:2020-12-25 07:42:52
【问题描述】:

在以下示例中,我遍历字典列表并将“年龄”保存在列表中。但是,第二个字典没有键“年龄”。在这种情况下,我希望将值 null 保存在列表中。关于如何实现这一点的任何建议?

my_list = [{'age': 0, 'name': 'A'}, {'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]

ages = [li['age'] for li in my_list] 

【问题讨论】:

  • dict.get(key, default=None)

标签: python python-3.x dictionary iterable


【解决方案1】:

您可以使用dict.get(key, default_value) 方法,如果键不存在,它将返回默认值。如果您不设置默认值,它将返回None

ages = [li.get('age', 0) for li in my_list] 

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 2012-07-04
    • 1970-01-01
    • 2012-07-07
    • 2023-03-14
    • 2021-10-16
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多