Jun-06-2021, 03:49 PM
(Jun-05-2021, 06:28 PM)perfringo Wrote: Maybe I am missing something but it seems that simple filtering functions would do. Something like:
lod = [{"id": 1, "a": 1, "b": 2, "result": 9.82}, {"id": 2, "a": 1, "b": 2, "result": -5}, {"id": 3, "a": 1, "b": 5, "result": 7.98}] def filter_dicts(data, *args, **kwargs): for row in data: for k, v in kwargs.items(): if row[k] != v: break else: yield {key: row[key] for key in args} print(*filter_dicts(lod, 'id', 'result', a=1, b=2)) # will print -> {'id': 1, 'result': 9.82} {'id': 2, 'result': -5}
this is a good solution but not a pythonic solution;
You should always try to avoid nested loop where possible and take advantage of list/dict comprehension;
and more --> try to simplify the problem -->
in this case You only need to know if kwargs' dict is a subset of the 'row' dict (as constraint made by OT) , no checking loop needed:
def filter_dicts(data, *args, **kwargs): return ({key: row[key] for key in args} for row in data if row.items() >= kwargs.items())