Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list of dict based on values from another dict

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
  • All elements in list_of_dicts have same keys.
  • dict_to_compare also have same keys as elements of list_of_dicts.
  • Multiple elements from list_of_dicts can be matched.
  • Values against any combination of two keys should be matched not all three.

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

like image 813
Sohaib Farooqi Avatar asked Nov 28 '17 15:11

Sohaib Farooqi


2 Answers

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'}]
like image 180
Ajax1234 Avatar answered Oct 25 '22 20:10

Ajax1234


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'}]
like image 39
Ma0 Avatar answered Oct 25 '22 19:10

Ma0