Reputation: 67
I have unlimited list of elements(they are rows in document db) containing dicts like:
list = [
{a:''}
{a:'', b:''}
{a:'',b:'',c:''}
]
And I have input - element, unlimited in count of it's dicts, like:
{a:'', c:''}
I need a function to find element index matching most dict keys with input. In this case it would be list[2], because it contains both {a:''} and {c:''}
Could you help me/prompt me how to do it?
Upvotes: 3
Views: 63
Reputation: 23780
You can use the builtin max
function and provide a matching key:
# 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())))
To extract the index in one pass:
max_index = max(enumerate(l), key=lambda item: len(t & set(item[1].keys())))[0]
Upvotes: 2
Reputation: 3523
>>> 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
Output
{'a': 'a', 'c': 'c', 'b': 'b'}
Upvotes: 0