简体   繁体   中英

Python how to get a value from a complex dictionary?

In dict1 below, how do I assign from_port to the value of 'FromPort' if I am unsure what index it will be in the 'IpPermissions'?

For the example below, I can use an index, but it is not always index 0.

from_port = dict1['IpPermissions'][0]['FromPort']

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

You can check if each element in the list has the attribute FromPort .

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

ip_permissions = dict1['IpPermissions']
for perm in ip_permissions:
    if 'FromPort' in perm:
        from_port = perm['FromPort']

Note: this doesn't handle the case if there is more than one dict with a 'FromPort' in it.

This approach will pull out any dictionary from the array that contains a 'FromPort' key.

tmp = [d for d in dict1['IpPermissions'] if 'FromPort' in d]
from_port = tmp[0]['FromPort']

Keep in mind this will fail if FromPort is not present (tmp will be empty) and similar to the other answer doesn't address multiple entries if you don't have that guarantee.

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