2017-08-19 51 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