ElasticThoughts ElasticThoughts - 26 days ago 8
Python Question

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
.

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


Ultimately, I need
pz-beanstalkd-asg-ec2
which is the
Value
of my EC2 instances
Name
tag.

The below code below prints out my dictionary...

How do I do get to
pz-beanstalkd-asg-ec2
using Python3?

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

Return type is
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'
},
]
}

Answer Source
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