如何检查字典列表中是否缺少键

时间:2019-02-16 18:54:20

标签: python-2.7

我希望能够从字典中检查是否缺少标签(LegalEntity),然后基于SnapshotId和VolumeId作为键/值对创建字典。

我尝试遍历字典,如代码所示,但出现以下错误:

Traceback (most recent call last):
File "tag.py", line 62, in <module>
tag_snapshots()
File "tag.py", line 39, in tag_snapshots
for tag in snapshot['Tags']:
KeyError: 'Tags'

字典对象如下

response = {
"Snapshots": [
    {
        "Description": "Snapshot1", 
        "Tags": [
            {
                "Value": "D_Snapshot", 
                "Key": "Name"
            }
        ], 
        "Encrypted": false, 
        "VolumeId": "vol-22222222222", 
        "State": "completed", 
        "VolumeSize": 60, 
        "StartTime": "2018-09-07T13:03:03.000Z", 
        "Progress": "100%", 
        "OwnerId": "222222222", 
        "SnapshotId": "snap-222222222"
    }, 
    {
        "Description": "Snapshot2", 
        "Tags": [
            {
                "Value": "C_Snapshot", 
                "Key": "Name"
            }
        ], 
        "Encrypted": false, 
        "VolumeId": "vol-333333333", 
        "State": "completed", 
        "VolumeSize": 60, 
        "StartTime": "2018-09-07T13:02:43.000Z", 
        "Progress": "100%", 
        "OwnerId": "3333333333", 
        "SnapshotId": "snap-3333333333"
    }
]
}

-------------------代码如下------------------------- ---------

snapshots = {}

def tag_snapshots():

for response in 
ec2.get_paginator('describe_snapshots').paginate(OwnerIds= 
['self']):
    for snapshot in response['Snapshots']:
        print(snapshot)
        for tag in snapshot['Tags']:
            if 'LegalEntity' not in tag:
                snapshots.update(
                    [(snapshot['SnapshotId'],
snapshot['VolumeId'])])

我的期望是,如果标签中未包含LegalEntity标记,则“快照”列表中该项目的SnapshotId和VolumeId将用于更新快照字典。

0 个答案:

没有答案