在 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'}

]}

我想要求name输入pipelineIdList并获得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()

在print(result)这种情况下, withinputString="Red"应该打印一个 值df-0004,但它完全不打印任何内容。任何有关解决此问题的帮助将不胜感激。


不负相思意
浏览 145回答 2
2回答

ABOUTYOU

我通常通过首先编写一个简单的函数来解决此类问题。正如@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解释:列表推导将其属性为所需颜色id的任何字典添加到列表中。由于所需颜色只有一个字典,因此列表的长度为 1。然后您访问该列表的第一个(也是唯一一个)元素,其索引为 0。pipelineIdListname
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python