简体   繁体   中英

extract value from python dict

{u'IamInstanceProfileAssociations': [{u'InstanceId': 'i-xxxxxxx', u'State': 'associated', u'AssociationId': 'iip-assoc-0xxxx', u'IamInstanceProfile': {u'Id': 'AIPAJxxxxx', u'Arn': 'arn:aws:iam::xxxxxx:instance-profile/Role'}}], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'xxxx-2cd4-4d92-bc30-xxxxx', 'HTTPHeaders': {'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'AmazonEC2', 'content-type': 'text/xml;charset=UTF-8', 'date': 'Fri, 09 Mar 2018 05:32:47 GMT'}}}

I have above output in a variable called response. How do I extract AssociationId value iip-assoc-0xxxx in python2.7 .

Thank you

you can try:

>>> d = {
    u'IamInstanceProfileAssociations': [{
        u'InstanceId': 'i-xxxxxxx',
        u'State': 'associated',
        u'AssociationId': 'iip-assoc-0xxxx',
        u'IamInstanceProfile': {
            u'Id': 'AIPAJxxxxx',
            u'Arn': 'arn:aws:iam::xxxxxx:instance-profile/Role'
        }
    }], 'ResponseMetadata': {
        'RetryAttempts': 0,
        'HTTPStatusCode': 200,
        'RequestId': 'xxxx-2cd4-4d92-bc30-xxxxx',
        'HTTPHeaders': {
            'transfer-encoding': 'chunked',
            'vary': 'Accept-Encoding',
            'server': 'AmazonEC2',
            'content-type': 'text/xml;charset=UTF-8',
            'date': 'Fri, 09 Mar 2018 05:32:47 GMT'
        }
    }
}
>>> print d["IamInstanceProfileAssociations"][0]['AssociationId']
'iip-assoc-0xxxx'
data = {u'IamInstanceProfileAssociations': [{u'InstanceId': 'i-xxxxxxx', u'State': 'associated', u'AssociationId': 'iip-assoc-0xxxx', u'IamInstanceProfile': {u'Id': 'AIPAJxxxxx', u'Arn': 'arn:aws:iam::xxxxxx:instance-profile/Role'}}], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'xxxx-2cd4-4d92-bc30-xxxxx', 'HTTPHeaders': {'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'AmazonEC2', 'content-type': 'text/xml;charset=UTF-8', 'date': 'Fri, 09 Mar 2018 05:32:47 GMT'}}}

print data["IamInstanceProfileAssociations"][0]['AssociationId']

I tried it here, https://www.jdoodle.com/python-programming-online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM