找到与另一个词典匹配的词典

时间:2017-08-19 07:07:51

标签: python json

我有无限的元素列表(它们是文档db中的行),包含像:

这样的字符串
list = [
{a:''}
{a:'', b:''}
{a:'',b:'',c:''}
]

我有输入 - 元素,无限数量,如:

{a:'', c:''}

我需要一个函数来查找与输入匹配大多数dict键的元素索引。 在这种情况下,它将是list [2],因为它包含{a:''}和{c:''}

你能帮助我/提示我该怎么做吗?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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