Python Forum
Compile list of dictianories out of another list of dictianories by certain keys - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Compile list of dictianories out of another list of dictianories by certain keys (/thread-33874.html)

Pages: 1 2


RE: Compile list of dictianories out of another list of dictianories by certain keys - perfringo - Jun-10-2021

(Jun-06-2021, 03:49 PM)Caprone Wrote: 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:

I agree that flat is better than nested. And I like subset idea.

But regarding 'pythonic'.... if we look at the the code provided then generator expression has also nested for-loop (albeit on one row) and character count is not in line with 'Limit all lines to a maximum of 79 characters.'. So, how should one judge this code from perspective of being 'pythonic'... Wink.

Applying 'pythonic' convention to tackle long line ('Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent'):

def filter_dicts(data, *args, **kwargs):
    return  ({key: row[key] for key in args}
              for row in data
              if row.items() >= kwargs.items())
and as OP already mentioned, these codes are not equal as give different results with different datasets. You know, all that stuff regarding errors passed silently.