【问题标题】:finding a specific value from list of dictionary in python从python中的字典列表中查找特定值
【发布时间】:2016-02-17 01:41:48
【问题描述】:

我的字典列表中有以下数据:

data = [{'I-versicolor': 0, 'Sepal_Length': '7.9', 'I-setosa': 0, 'I-virginica': 1},
{'I-versicolor': 0, 'I-setosa': 1, 'I-virginica': 0, 'Sepal_Width': '4.2'},
{'I-versicolor': 2, 'Petal_Length': '3.5', 'I-setosa': 0, 'I-virginica': 0},
{'I-versicolor': 1.2, 'Petal_Width': '1.2', 'I-setosa': 0, 'I-virginica': 0}]

为了获得基于键和值的列表,我使用以下方法:

next((item for item in data if item["Sepal_Length"] == "7.9"))

但是,所有字典都不包含键 Sepal_Length,我得到了:

KeyError: 'Sepal_Length'

我该如何解决这个问题?

【问题讨论】:

  • 这个问题让我觉得list.index 应该采用可选的key,如list.sort,用作谓词...
  • @Claudiu -- 这是一个有趣的想法。我经常使用这个next 成语,但它有一些夸克(例如,如果您不确定是否会找到匹配项,则提供默认值)

标签: python dictionary python-3.5


【解决方案1】:

你可以使用dict.get获取值:

next((item for item in data if item.get("Sepal_Length") == "7.9"))

作为奖励,您实际上不需要在生成器表达式周围加上额外的括号:

# Look mom, no extra parenthesis!  :-)
next(item for item in data if item.get("Sepal_Length") == "7.9")

但如果您想指定默认值,它们会有所帮助:

next((item for item in data if item.get("Sepal_Length") == "7.9"), default)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2018-08-30
    • 2023-01-07
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多