I have the following dictionary and list:
dict = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z'],
'four':['xx','yy']}
ls = ['a','x','c','h','l']
I need to loop through the dict values and check if the items in ls exist in dict values, if so I would like to return a new dict with key/pair values, as follows:
new_dict = {'one':['a','c'],'two':['h','l'], 'three':['x']}
CodePudding user response:
You can check overlaps with a set intersection -
new_dict = {k: list(set(v) & set(ls)) for k, v in dct.items() if (set(v) & set(ls))}
Output
{'one': ['c', 'a'], 'two': ['l', 'h'], 'three': ['x']}
CodePudding user response:
_dict = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z']}
ls = ['a','x','c','h','l']
new_dict = {k:[v for v in l if v in ls] for k,l in _dict.items()}
print(new_dict)
CodePudding user response:
First, a tip: you should never call variablke as "orange names" like int, float, dict, input, exc...
The solution:
dictt = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z']}
ls = ['a','x','c','h','l']
for k, v in dictt.items():
dictt[k] = [el for el in v if el in ls]