2014-10-19 104 views
1

我有一個字典列表,我想查找一個值是否在列表中存在,如果存在則返回字典。 例如搜索python中的字典列表

Mylist= [{'Stringa': "ABC", 
      'Stringb': "DE", 
      'val': 5}, 
      {'Stringa': "DEF", 
      'Stringb': "GHI", 
      'val': 6}] 

我想以發現任何字典

的dict [ 「stringa」] == 「ABC」。如果是,則返回相應的字典。 我使用的功能「任何」

any(d['Stringa'] == 'ABC' for d in Mylist) 

,但它只是給真/假。我怎樣才能得到相應的字典。

回答

1

any將只檢查迭代中的任何項目是否滿足條件。它不能用於檢索匹配的項目。

使用列表理解來獲得相匹配的項目清單,這樣

matches = [d for d in Mylist if d['Stringa'] == 'ABC'] 

這將在字典中的列表循環,每當找到一個匹配,這將包括在結果列表中。然後,您可以使用列表中的索引訪問實際詞典,如matches[0]

或者,您可以用生成器表達式,像這樣

matches = (d for d in Mylist if d['Stringa'] == 'ABC') 

,你可以從列表中獲取下一個匹配的項目,與

actual_dict = next(matches) 

這會給你的實際字典。如果您想獲得下一個匹配項目,可以再次使用生成器表達式調用next。如果你想獲得的所有匹配項一次,作爲一個列表,你可以簡單地做

list_of_matches = list(matches) 

注:調用next()將引發異常,如果沒有從發電機獲取更多項目。所以,你可以傳遞一個默認值來返回。

actual_dict = next(matches, None) 

現在,actual_dictNone如果發電機被耗盡。

1

這裏是另一種選擇,它可以讓你多一點靈活性:

def search_things(haystack, needle, value): 
    for i in haystack: 
     if i.get(needle) == value: 
     return i 
    return None # Not needed, None is returned by default 
       # you can use this to return some other default value 

found = search_things(MyList, 'StringA', 'ABC') 
if found: 
    print('Found it! {}'.format(found)) 
else: 
    print('Not found')