I have a list of dictionaries list_of_dict
, a set of keys set_of_keys
and another dictionary dict_to_compare
.
I need to filter the list of dicts if the values of any two of the three possible keys matches the values from dict_to_compare
.
Input:
set_of_keys = {'val1', 'val2', 'val3'}
dict_to_compare = {'k1': 'val1', 'k2': 'val2','k3':'val6'}
list_of_dict = [
{'k1': 'val1', 'k2': 'val2', 'k3':'val3'},
{'k1': 'val4', 'k2': 'val5', 'k3':'val6'},
{'k1': 'val7', 'k2': 'val8', 'k3':'val9'}
]
Output:
out = [{'k1': 'val1', 'k2': 'val2', 'k3': 'val3'}] #First element from list
list_of_dicts
have same keys.dict_to_compare
also have same keys as elements of list_of_dicts
.list_of_dicts
can be matched.I tried doing this by explicitly specifying bunch of if
elif
conditions. But the problem is set of keys is really huge. Is there a better way to solve this?
Thanks
You can use sum
:
dict_to_compare = {'k1': 'val1', 'k2': 'val2','k3':'val6'}
set_of_keys = {'val1', 'val2', 'val3'}
list_of_dict = [
{'k1': 'val1', 'k2': 'val2', 'k3':'val3'},
{'k1': 'val4', 'k2': 'val5', 'k3':'val6'},
{'k1': 'val7', 'k2': 'val8', 'k3':'val9'}
]
final_list = [i for i in list_of_dict if sum(c in set_of_keys for c in i.values()) >= 2]
Output:
[{'k3': 'val3', 'k2': 'val2', 'k1': 'val1'}]
You can recreate the list_of_dict
using a list-comprehension that features your desired filtering scheme:
set_of_keys = {'val1', 'val2', 'val3'}
dict_to_compare = {'k1': 'val1', 'k2': 'val2','k3':'val6'}
list_of_dict = [
{'k1': 'val1', 'k2': 'val2', 'k3':'val3'},
{'k1': 'val4', 'k2': 'val5', 'k3':'val6'},
{'k1': 'val7', 'k2': 'val8', 'k3':'val9'}
]
list_of_dict = [d for d in list_of_dict if sum(1 for k, v in d.items() if dict_to_compare.get(k, None)==v)>1]
print(list_of_dict) # -> [{'k1': 'val1', 'k2': 'val2', 'k3': 'val3'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With