2016-01-12 48 views
6

我想從包含元組和字典的列表中獲取特定字典。我將如何去從下面的列表中返回帶有'k'鍵的字典?列表中包含的元組和字典

lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}] 

回答

7

爲了您

lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}] 
使用

next(elem for elem in lst if isinstance(elem, dict) and 'k' in elem) 

回報

{'k': [1, 2, 3]} 

即你的第一個對象r列表,它是一個字典幷包含密鑰'k'。

如果找不到這樣的對象,則會產生StopIteration。如果您想返回其他內容,例如None,使用此:

next((elem for elem in lst if isinstance(elem, dict) and 'k' in elem), None) 
6
def return_dict(lst): 
    for item in lst: 
     if isinstance(item,dict) and 'k' in item: 
      return item 
    raise Exception("Item not found") 
0

如果你不介意在你的代碼,我會遍歷目錄,查看每個元素有點難看。例如:

def find_dict(lst): 
    for element in lst: 
     if type(element) == dict: 
      if 'k' in element.keys(): 
       return element 

這應該是一個更pythonic的方式可能。

+1

打字太久了.. teamProbable贏了! – Skirrebattie