从python dict中提取值

时间:2018-03-09 05:40:39

标签: python python-2.7 boto3

{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'}}}

我在一个名为response的变量中有上面的输出。如何在iip-assoc-0xxxx中提取AssociationId值python2.7

谢谢

2 个答案:

答案 0 :(得分:1)

你可以尝试:

>>> 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'

答案 1 :(得分:1)

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']

我在这里试了一下,https://www.jdoodle.com/python-programming-online