【问题标题】:how to by pass Python key error even when key is present?即使存在密钥,如何绕过 Python 密钥错误?
【发布时间】:2018-08-17 16:37:51
【问题描述】:

错误

蟒蛇code

即使存在密钥,我也会收到密钥错误。

print (dict_month[0:4])

[{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

'January' in dict_month

错误

'january' in dict_month

错误

【问题讨论】:

  • 'January' in i for i in dict_month
  • 你有一个字典列表,而不是字典……一月不是 dict_month 的键,它是你所有字典的键。

标签: python list dictionary keyerror


【解决方案1】:

简单的一个班轮:

>>> any(['January' in ele for ele in l])

#driver 值:

IN : l = [{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

OUT : True

正如 A.Joly 所提到的,您的方法存在问题,即您有一个 list of dictionary。对于dictionary,您的方法是正确的。

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2020-12-11
    • 1970-01-01
    • 2017-10-01
    • 2016-02-17
    • 2020-07-23
    相关资源
    最近更新 更多