簡體   English   中英

Python如何從復雜的字典中獲取值?

[英]Python how to get a value from a complex dictionary?

在下面的 dict1 中,如果我不確定它在“IpPermissions”中的索引,我如何將 from_port 分配給“FromPort”的值?

對於下面的示例,我可以使用索引,但它並不總是索引 0。

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

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

您可以檢查列表中的每個元素是否具有屬性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']

注意:如果有多個帶有'FromPort' dict,這將無法處理這種情況。

這種方法將從包含“FromPort”鍵的數組中提取任何字典。

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

請記住,如果 FromPort 不存在(tmp 將為空),這將失敗,並且與其他答案類似,如果您沒有該保證,則不會解決多個條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM