2015-12-08 49 views
0

我有一段代碼來獲取字典中已定義鍵的值。它的偉大工程,並返回一個列表,但現在我想獲得更多的1鍵和可能保存到一個字典從Python字典中查詢2個鍵

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,我可以運行此函數兩​​次來實現我的目標但想知道如何修改,所以我只運行一次。

編輯:我的目標是獲得SnapshotId,然後從以下詞典StartTime值,會有好幾個被退回

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

Snapshots名單這是我當前的代碼:

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))) 
+2

只需通過一個列表而不是一個鍵,然後調用它的鍵,然後檢查'如果鍵k' –

+0

或,有一個更好的界面:'def find(dictionary,* keys)' –

+0

對不起,我很困惑,我只需要傳遞一個具有相同函數的列表,或者我需要在函數中添加更多代碼? – Casper

回答

0

如果你有嚴格的結構,不要遍歷所有的值。相反:

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

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

爲ID->的時間字典。

+0

我不知道Python,我該如何使用它?它是一個函數? – Casper