从 Python 字典中查询 2 个键

Query 2 keys from Python dict

我有一段代码可以获取字典中已定义键的值。它很好用,return 是一个列表,但现在我想再获得 1 个密钥,并可能将其保存到字典中

def find(key, dictionary):
    for k, v in dictionary.iteritems():
        if k == key:
            yield v
        elif isinstance(v, dict):
            for result in find(key, v):
                yield result
        elif isinstance(v, list):
            for d in v:
                for result in find(key, d):
                    yield result

我不太了解Python,我可以运行这个函数两次来达到我的目的,但想知道如何修改它所以我只运行一次。

编辑:我的目标是从以下字典中获取 SnapshotIdStartTime 的值,将有几个 Snapshots 列表被 returned

{
    'Snapshots': [
        {
            'SnapshotId': 'string',
            'VolumeId': 'string',
            'State': 'pending'|'completed'|'error',
            'StateMessage': 'string',
            'StartTime': datetime(2015, 1, 1),
            'Progress': 'string',
            'OwnerId': 'string',
            'Description': 'string',
            'VolumeSize': 123,
            'OwnerAlias': 'string',
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'Encrypted': True|False,
            'KmsKeyId': 'string',
            'DataEncryptionKeyId': 'string'
        },
    ],
    'NextToken': 'string'
}

这是我当前的代码:

def find(keys, dictionary):
    for k, v in dictionary.iteritems():
        if k in keys:
            yield v
        elif isinstance(v, dict):
            for result in find(key, v):
                yield result
        elif isinstance(v, list):
            for d in v:
                for result in find(key, d):
                    yield result

def findDate(key, dictionary):
    for k, v in dictionary.iteritems():
        if k == key:
            yield v
        elif isinstance(v, dict):
            for result in find(key, v):
                yield result.strftime('%Y/%m/%d')
        elif isinstance(v, list):
            for d in v:
                for result in find(key, d):
                    yield result.strftime('%Y/%m/%d')   

    response = ec2.describe_snapshots(
        Filters=[
            {
                'Name': 'volume-id',
                'Values': [
                    VOLUMEID,
                ]
            },
        ]
    )

    recentSnapshots_id = list(find('SnapshotId', response))

    recentSnapshots_date = list(findDate('StartTime', response))

    print (dict(zip(recentSnapshots_id, recentSnapshots_date)))

如果您有严格的结构,请不要遍历所有值。相反:

[{'SnapshotId': s['SnapshotId'], 'StartTime':s['StartTime']}  for s in data['Snapshots']]

{ s['SnapshotId']:s['StartTime'] for s in data['Snapshots'] }

对于 id->time 字典。