简体   繁体   English

在 Python 字典中查找元素

[英]Find Elements in Python Dict

I am getting a python dictionary from AWS which is formatted like the following sample object:我从 AWS 获取了一个 python 字典,它的格式类似于以下示例对象:

{'ResponseMetadata': {'NOT IMPORTANT'},
 'hasMoreResults': True,
 'marker': '{"NOT IMPORTANT"}',
 'pipelineIdList': [{'id': 'df-0001',
                     'name': 'Blue'},
                    {'id': 'df-0002',
                     'name': 'Orange'},
                    {'id': 'df-0003',
                     'name': 'Green'},
                    {'id': 'df-0004',
                     'name': 'Red'},
                    {'id': 'df-0005',
                     'name': 'Purple'}
]}

I want to ask for the name of an input in pipelineIdList and get the id that matches with it.我想在pipelineIdList询问输入的name并获取与其匹配的id For example, if you search using the input string "Red" you will get a return value of "df-0004"例如,如果您使用输入字符串“Red”进行搜索,您将获得“df-0004”的返回值

My code is as follows:我的代码如下:

import boto3

def findId(pipeline_list, inputString):
  for dict in pipeline_list:
    if dict['pipelineIdList']['name'] == inputString:
      return dict['id']

def main():
  inputString = "Red"

  datapipeline = boto3.client('datapipeline')
  pipeline_list = datapipeline.list_pipelines() //This line returns a Dict like the one above

  result = findId(pipeline_list, inputString)
  print(result)


if __name__ == "__main__":
  main()

The print(result) in this case with inputString="Red" should print a value of df-0004 , but it instead prints absolutely nothing.在这种情况下,带有inputString="Red"print(result)应该打印df-0004的值,但它绝对不打印任何内容。 Any help with fixing this issue would be greatly appreciated.任何解决此问题的帮助将不胜感激。

I normally approach problems like this by first writing a simple function.我通常通过首先编写一个简单的函数来解决这样的问题。 Once you understand the bare bones, you can get fancier and attempt code optimization via something like list comprehension, as suggested by @Maribeth Cogan.一旦您了解了基本原理,您就可以像@Maribeth Cogan 所建议的那样,通过诸如列表理解之类的东西来尝试代码优化。

def findId(obj_dictionary, color):
    lst = obj_dictionary['pipelineIdList']
    for dictionary in lst:
        if dictionary['name'] == color:
            return(dictionary['id'])

We extract the list we want to look at from the given dictionary, then go through the elements of that list to find the dictionary element whose value matches the given color target.我们从给定的字典中提取我们想要查看的列表,然后遍历该列表的元素以找到其值与给定color目标匹配的字典元素。 Then, the method returns the key corresponding to that dictionary element.然后,该方法返回与该字典元素对应的键。

a simple list comprehension can solve your problem.一个简单的列表理解可以解决您的问题。 Try running this code:尝试运行此代码:

my_color='Red'

result = [colorDict['id'] for colorDict in d['pipelineIdList'] if colorDict['name']==my_color][0]

the value of result should now be df-0004 result的值现在应该是df-0004

Explanation : the list comprehension adds to a list the id of any dictionary in the pipelineIdList whose name property is the desired color.说明:列表推导式将pipelineIdList name属性为所需颜色的任何字典的id添加到列表中。 Since there is only one dictionary for the desired color, the length of the list is 1. Then you access the first (and only) element of that list, which has index 0.由于所需颜色只有一个字典,因此列表的长度为 1。然后访问该列表的第一个(也是唯一一个)元素,该元素的索引为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM