如何检查Python中字典列表中是否存在键/值?

时间:2019-07-08 11:59:56

标签: python-2.7 list dictionary

对于下面给出的字典列表的字典,我想检查键值"url": "/Province/?ID=83"是否存在于字典列表中。

data = {
          "current_page": 1,
          "data": [
              {
                  "columns": [
                      {
                          "key": "ID",
                          "value": "83"
                      },
                      {
                          "key": "Description",
                          "value": "Test Curring"
                      },
                      {
                          "key": "LocalDescription",
                          "value": "tests curring"
                      }
                  ],
                  "important": [
                      {
                          "key": "ID",
                          "value": "83"
                      },
                      {
                          "key": "Description",
                          "value": "Test Curring"
                      },
                      {
                          "key": "LocalDescription",
                          "value": "tests curring"
                      }
                  ],
                  "url": "/Province/?ID=83"
              },
              {
                  "columns": [
                      {
                          "key": "ID",
                          "value": "82"
                      },
                      {
                          "key": "Description",
                          "value": "Test 81 Description"
                      },
                      {
                          "key": "LocalDescription",
                          "value": "Local Test Description"
                      }
                  ],
                  "important": [
                      {
                          "key": "ID",
                          "value": "82"
                      },
                      {
                          "key": "Description",
                          "value": "Test 81 Description"
                      },
                      {
                          "key": "LocalDescription",
                          "value": "Local Test Description"
                      }
                  ],
                  "url": "/Province/?ID=82"
              },
          ]
      }

我知道它的存在,如何检查返回TrueFalse的存在?

我尝试过:

list_data = data.get('data')

index = 0
for item in list_data:
  url = item[0].get('url')
  index += 1
  print 'url: ',url

但是,我遇到了错误:

    url = item[0].get('url')
KeyError: 0

2 个答案:

答案 0 :(得分:5)

这是通过收集url中每个项目的data['data']并查看其中是否包含所需的值来实现的;假设data['data']中的每个项目都有一个url元素。

"/Province/?ID=83" in [x['url'] for x in data['data']]

答案 1 :(得分:2)

假设data的架构是一致的,则可以尝试以下操作: 如果数据中存在True,它将返回key:value,否则将返回False

  def check(data, key, value):
      for i in data['data']:
        try:
          if(i[key]==value): return True
        except:
          pass
      return False