Home > Mobile >  Filter a dictionary based on a list
Filter a dictionary based on a list

Time:10-23

I have a dictionary with values in CamelCase sensitive and I'd like to filter the dictionary values based on a list of lower case elements:

d = {'1a': ['DW_TEST (DEV)', 'public', 'Labs'],
     '1b': ['DW_TEST (DEV)', 'public', 'Test'],
     '1c': ['DW_TEST (PROD)', 'public', 'Labs'],
     '1d': ['DW_TEST (PROD)', 'public', 'Test'],
     '2a': ['DW_PROD (PROD)', 'public', 'Medications'],
     '2b': ['DW_PROD (DEV)', 'public', 'Med_Test']}

l = [['dw_test (dev)', 'public', 'labs'],
     ['dw_test (prod)', 'public', 'labs'],
     ['dw_prod (prod)', 'public', 'medications']]

Expected dictionary:

d = {'1a': ['DW_TEST (DEV)', 'public', 'Labs'],
         '1c': ['DW_TEST (PROD)', 'public', 'Labs'],
         '2a': ['DW_PROD (PROD)', 'public', 'Medications']}

I know how to filter based on dictionary keys but I'd like to filter dictionary values based on a list.

CodePudding user response:

One approach is to convert l into a set of tuples (lookup) and then filter out those items which value is not present in the set:

lookup = set(tuple(li) for li in l)
result = {key: value for key, value in d.items() if tuple(map(str.lower, value)) in lookup}
print(result)

Output

{'1a': ['DW_TEST (DEV)', 'public', 'Labs'], '1c': ['DW_TEST (PROD)', 'public', 'Labs'], '2a': ['DW_PROD (PROD)', 'public', 'Medications']}

CodePudding user response:

You can do it by passing through string comparison like this :

l = [str(i) for i in l]
new_dict = {key:value for (key,value) in d.items() if str(value).lower() in l}

CodePudding user response:

d = {'1a': ['DW_TEST (DEV)', 'public', 'Labs'],
     '1b': ['DW_TEST (DEV)', 'public', 'Test'],
     '1c': ['DW_TEST (PROD)', 'public', 'Labs'],
     '1d': ['DW_TEST (PROD)', 'public', 'Test'],
     '2a': ['DW_PROD (PROD)', 'public', 'Medications'],
     '2b': ['DW_PROD (DEV)', 'public', 'Med_Test']}

l = [['dw_test (dev)', 'public', 'labs'],
     ['dw_test (prod)', 'public', 'labs'],
     ['dw_test (prod)', 'public', 'medications']]

d_l = { k:[ii.lower() for ii in i] for k,i in d.items() }
l_l = [[ii.lower() for ii in i] for i in l]
o = {}
for key, value in d_l.items():
    for item in l_l:
        if item == value:
            o[key] = d[key]
print(o)

This should work, converting both lists/dict into lower case, comparing and then appending from the original list

  • Related