list of dictionaries search using kwargs

Larry Martell larry.martell at gmail.com
Mon Dec 7 17:06:39 EST 2020


I have a class that has an object that contains a list of dicts. I
want to have a class method that takes a variable number of key/value
pairs and searches the list and returns the item that matches the
arguments.

If I know the key value pairs I can do something like this:

instance = next(item for item in data] if\
           item["appCode"] == 1 and\
           item["componentCode"] == "DB" and\
           item["environmentEnumID"] == 12 and\
           item["serverName"] == 'foo', None)

But in my class method if I have:

    def find_data_row(self, **kwargs):

and I call it:

find_data_row(appCode=1, componentCode='DB', ...)

How can I do the search in a pythonic way?


More information about the Python-list mailing list