2017-08-19 37 views
3

我有元素的無限列表包含類似類型的字典(它們在文檔DB行):查找字典匹配另一個字典

list = [ 
{a:''} 
{a:'', b:''} 
{a:'',b:'',c:''} 
] 

而且我有輸入 - 元素,無限在它伯爵的類型的字典,如:

{a:'', c:''} 

我需要一個函數來查找匹配大多數字典鍵與輸入的元素索引。 在這種情況下,它將列表[2],因爲它包含{a:''}和{c:''}

你能幫我/提示我該怎麼做嗎?

+1

'unlimited list' really ambitious –

+0

遍歷列表尋找匹配的項目。 –

+0

爲什麼不能列表[3],因爲它也包含{a:''}和{c:''}? –

回答

2

可以使用內置max函數並提供匹配的鍵:

# The input to search over 
l = [{'a':''}, {'a':'', 'b':''}, {'a':'','b':'','c':''}] 
# Extract the keys we'd like to search for 
t = set({'a': '', 'c': ''}.keys()) 

# Find the item in l that shares maximum number of keys with the requested item 
match = max(l, key=lambda item: len(t & set(item.keys()))) 

要提取的索引在一遍:

max_index = max(enumerate(l), key=lambda item: len(t & set(item[1].keys())))[0] 
+0

太棒了 – gGotcha

0
>>> lst = [{'a':'a'},{'a':'a','b':'b'},{'a':'a','b':'b','c':'c'}] 
>>> seen = {} 
>>> [seen.update({key:value}) for dct in lst for key,value in dict(dct).items() if key not in seen.keys()] 

>>> seen 

輸出

{'a': 'a', 'c': 'c', 'b': 'b'} 

check here