在Python Dict中查找元素

2024-03-29 04:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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'}
]}

我想在pipelineIdList中请求输入的name,并获取与之匹配的id。例如,如果使用输入字符串“Red”进行搜索,则返回值为“df-0004”

我的代码如下:

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()

在这种情况下,带有inputString="Red"print(result)应该打印df-0004的值,但是它完全不打印任何内容。如果您能帮助解决此问题,我们将不胜感激


Tags: nameiddfpipelinemainnotredresult
2条回答

我通常先编写一个简单的函数来解决这样的问题。一旦你了解了这些基本内容,你就可以变得更加有趣,并尝试通过类似列表理解的方式来优化代码,正如@Maribeth Cogan所建议的那样

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

我们从给定的字典中提取我们想要查看的列表,然后遍历该列表的元素以找到其值与给定的color目标匹配的字典元素。然后,该方法返回对应于该字典元素的键

简单的列表理解可以解决您的问题。尝试运行以下代码:

my_color='Red'

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

result的值现在应该是df-0004

解释:列表理解将pipelineIdList中任何词典的id添加到列表中,该词典的name属性是所需的颜色。由于所需颜色只有一个字典,因此列表的长度为1。然后访问该列表的第一个(也是唯一一个)元素,该元素的索引为0

相关问题 更多 >