【问题标题】:Nested Dictionary Parsing - Python 3嵌套字典解析 - Python 3
【发布时间】:2017-09-23 20:17:24
【问题描述】:

我有一本字典。我需要遍历父字典,直到找到包含指定键和值对的嵌套字典。我关心的键值对是:

key=Key, value=Name

一旦我通过找到这个Name 标签找到了正确的嵌套字典,然后我需要拉出key=Value 的嵌套字典value

key=Value, value=pz-beanstalkd-asg-ec2

最终,我需要 pz-beanstalkd-asg-ec2,这是我的 EC2 实例 Name 标签的 Value

下面的代码打印出我的字典...

如何使用 Python3 访问 pz-beanstalkd-asg-ec2

print ('lenth of dict=' + str(len(instanceTagsDict['Tags'])))
    for x in range(0, len(instanceTagsDict['Tags'])):
        print('x=' + str(x))
        for key, value in instanceTagsDict['Tags'][x].items():
            print('key=' + key + ', value=' + value)


lenth of dict=5
x=0
key=Key, value=AWSService
key=ResourceId, value=i-0dd3a48d19fbc0aa7
key=ResourceType, value=instance
key=Value, value=ec2
x=1
key=Key, value=Application
key=ResourceId, value=i-0dd3a48d19fbc0aa7
key=ResourceType, value=instance
key=Value, value=myallocator
x=2
key=Key, value=Environment
key=ResourceId, value=i-0dd3a48d19fbc0aa7
key=ResourceType, value=instance
key=Value, value=production
x=3
key=Key, value=Name
key=ResourceId, value=i-0dd3a48d19fbc0aa7
key=ResourceType, value=instance
key=Value, value=pz-beanstalkd-asg-ec2
x=4
key=Key, value=aws:autoscaling:groupName
key=ResourceId, value=i-0dd3a48d19fbc0aa7
key=ResourceType, value=instance
key=Value, value=pz-beanstalkd-asg

我调用的函数是 describe_tags,文档在这里:http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_tags

返回类型是 字典

响应语法是

{
    'NextToken': 'string',
    'Tags': [
        {
            'Key': 'string',
            'ResourceId': 'string',
            'ResourceType': 'customer-gateway'|'dhcp-options'|'image'|'instance'|'internet-gateway'|'network-acl'|'network-interface'|'reserved-instances'|'route-table'|'snapshot'|'spot-instances-request'|'subnet'|'security-group'|'volume'|'vpc'|'vpn-connection'|'vpn-gateway',
            'Value': 'string'
        },
    ]
}

【问题讨论】:

  • 你能给个json样本吗?测试起来会容易得多。
  • 你的例子是一个字典列表,而不是字典的字典

标签: python python-3.x amazon-web-services dictionary amazon-ec2


【解决方案1】:
def findval(mykey, myval):
  for item in instanceTagsDict['Tags']:
    if mykey in item and item[mykey] == myval:
      print(item['Value'])

去做吧!

>>> findval('Key', 'Name')
pz-beanstalkd-asg-ec2

【讨论】:

    猜你喜欢
    • 2018-09-05
    • 2019-01-18
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2013-07-28
    • 2011-06-06
    相关资源
    最近更新 更多