【问题标题】:How to make a python dictionary key error return false如何使python字典键错误返回false
【发布时间】:2016-04-30 22:11:12
【问题描述】:

我正在处理具有动态响应结构(键)的 JSON 数据集,如果存在某些键,则需要执行代码。现在,如果该键不存在,它会引发一个键错误,我试图通过一个 bool 操作数传递该键错误,但在 Python 中,该键错误似乎胜过 bool 操作数。

bool(dictionary['key'])

KeyError: 'key'

我觉得有一些方法可以做到这一点,这比我尝试的更容易,但只是无法通过研究找到任何东西。任何帮助将不胜感激。

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    你想要dictionary.get('key')。默认情况下,这将返回None,其计算结果为False

    【讨论】:

    • 当字典很浅时,这是一个很好的方法,但是 JSON 数据集可能是分层的,我需要一些迭代整个数据结构的东西,以便有时检查 2 或 3 级深度的键。有没有一种简单的方法可以做到这一点?
    • @JackBurton try / except KeyError: 可能对此有用。
    • @JackBurton 你的意思是你想要一个函数递归地检查一个键吗?这要复杂得多,而且您可能不希望每次需要键值时都进行这种搜索。
    • @RushyPanchal 正确。 JSON结构是这样的: {dictionary1 {dictionary2 [list {dictionary3}] } } 我在dictionary3中的键之后,列表中的每个项目可能存在也可能不存在。列表对象中可能有多个 dictionary3 迭代。
    • 杰克:您需要显示正在搜索的字典的结构修改您的问题(及其标题)以反映您的真实问题。
    【解决方案2】:

    使用dict.get 并在未找到密钥时设置默认值

    dictionary.get('key', 'NotFound')
    

    【讨论】:

      【解决方案3】:

      您是否尝试过使用dictionary.has_key(key_name),如果密钥存在,此方法将返回 true,否则返回 false。

      【讨论】:

      • 更好地使用key_name in dictionary 测试。
      【解决方案4】:

      你想要这样的东西吗?

      #!python3
      json_data = [
              { 'key1':
                  { 'key2':
                      [
                          {'key3': 1 }
                          ]
                      }
                  }
              ]
      
      def get_deep(*keys):
          try:
              doa = json_data
              for key in keys:
                  doa = doa[key]
              return doa
          except KeyError:
              return None
          except IndexError:
              return None
      
      tests = (
          # Want, Keys...
          (1, 0, 'key1', 'key2', 0, 'key3'),
          (None, 1, 'key1', 'key2', 0, 'key3'),
          (None, 0, 'key11', 'key2', 0, 'key3'),
          (None, 0, 'key1', 'key22', 0, 'key3'),
          (None, 0, 'key1', 'key2', 1, 'key3'),
          (None, 0, 'key1', 'key2', 0, 'key33'),
      )
      
      
      for i,test in enumerate(tests):
          expected,*keys = test
          got = get_deep(*keys)
          if got is expected:
              print(i, "OK")
          else:
              print(i, "FAIL", got, "is not", expected)
      

      【讨论】:

        猜你喜欢
        • 2015-07-24
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多