list of dictionaries search using kwargs

MRAB python at mrabarnett.plus.com
Mon Dec 7 18:06:47 EST 2020


On 2020-12-07 22:06, Larry Martell wrote:
> 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?
> 
An item is a match if:

     all(item[key] == value for key, value in kwargs.items())

or possibly:

     MISSING = object()

     all(item.get(key, MISSING) == value for key, value in kwargs.items())

Just iterate over the list of dicts until you find a match.


More information about the Python-list mailing list