Home > Software design >  How to filter the dictionary by the list correctly
How to filter the dictionary by the list correctly

Time:10-06

There is a dictionary and a list of dictionaries. It is necessary to filter the dictionary by key, excluding duplicate values that are in the list (name).

dict1 = {'code': 'varchar(25)', 'cnt': 'int', 'id': 'int'}

lst1 = [{'name': 'client', 'datatype': 'varchar(100)'}, {'name': 'id', 'datatype': 'int'}, {'name': 'status', 'datatype': 'varchar(10)'}]

Return:

dict2 = {'code': 'varchar(25)', 'cnt': 'int'}

CodePudding user response:

Make a set of the names from lst1:

>>> names = {d['name'] for d in lst1}
>>> names
{'id', 'client', 'status'}

and then make a dict that excludes keys that are in that set:

>>> {k: v for k, v in dict1.items() if k not in names}
{'code': 'varchar(25)', 'cnt': 'int'}
  • Related