【问题标题】:Want to access a value in a dictionary which is inside a list inside another dictionary想要访问另一个字典中的列表中的字典中的值
【发布时间】:2015-06-22 12:48:14
【问题描述】:

我将 Python3 与 boto3 包一起使用,并且正在运行 describe_instances() 来描述我的所有实例。但是返回类型是字典,现在字典中有列表和其他字典。

例如,我想要做的是仅返回“InstanceId”字符串,或者如果我可以返回也不错的整个“Instances”列表。

ec2 = boto3.client(Make connection here)
response = ec2.describe_instances()
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(response)

返回类型和响应代码可以在这里找到。 http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.describe_instances

【问题讨论】:

    标签: python amazon-web-services boto3


    【解决方案1】:

    您可以将所有 InstanceID 的列表作为列表获取,例如

    import itertools
    instance_list = list(itertools.chain.from_iterable([[i.get("InstanceId") for i in r.get("Instances", [])] for r in response['Reservations']]))
    

    【讨论】:

    • 这正是我希望它工作的方式。但是,您能否稍微解释一下语法。在这里完成 Python 新手。
    • i.get("key", default) 如果字典中不存在该键,则返回默认值; [f(i) for i in x] 是一个列表理解表达式,它通过迭代和评估 x 的每个元素的 f(i) 来构建一个列表。因此,它或多或少等同于the_list = []; for i in x: the_list.append(f(i)),但从未将该列表分配给变量。
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2017-07-29
    相关资源
    最近更新 更多