[英]Nested Dictionary Parsing - Python 3
I have a dictionary of dictionaries. 我有字典词典。 I need to iterate through the parent dictionary until I find the nested dict which contains a specify key and value pair.
我需要遍历父字典,直到找到包含指定键和值对的嵌套字典。 The key and value pair that I care about is:
我关心的关键和价值对是:
key=Key, value=Name
Once I've located the proper nested dict by finding this Name
tag, I then need to pull out that nested dicts value
of key=Value
. 通过找到此
Name
标签找到正确的嵌套字典后,我需要提取key=Value
嵌套字典value
。
key=Value, value=pz-beanstalkd-asg-ec2
Ultimately, I need pz-beanstalkd-asg-ec2
which is the Value
of my EC2 instances Name
tag. 最后,我需要
pz-beanstalkd-asg-ec2
这就是Value
我的EC2实例的Name
标签。
The below code below prints out my dictionary... 下面的代码打印出我的字典...
How do I do get to pz-beanstalkd-asg-ec2
using Python3? 如何使用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
The function I'm calling is describe_tags, docs here: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_tags 我正在调用的函数是describe_tags,位于此处的文档: http : //boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_tags
Return type is dict 返回类型为 dict
Response Syntax is 响应语法为
{
'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'
},
]
}
def findval(mykey, myval):
for item in instanceTagsDict['Tags']:
if mykey in item and item[mykey] == myval:
print(item['Value'])
Do It! 做吧!
>>> findval('Key', 'Name')
pz-beanstalkd-asg-ec2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.