从Python dict查询2个键

时间:2015-12-08 22:46:40

标签: python amazon-web-services dictionary aws-lambda

我有一段代码来获取dict中已定义键的值。它工作得很好,并返回一个列表,但现在我想再获得一个密钥并可能将其保存到一个字典

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列表

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

1 个答案:

答案 0 :(得分:0)

如果你有严格的结构,不要迭代所有的值。代替:

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

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

获取id->时间词典。