list of dictionaries search using kwargs

Larry Martell larry.martell at gmail.com
Mon Dec 7 17:53:37 EST 2020


On Mon, Dec 7, 2020 at 5:42 PM Matt Wheeler <m at funkyhat.org> wrote:
>
> for item in self.data:
>     if all(item[k] == v for k,v in kwargs.items()):
>         return item
>
> Or
>
> return [item for item in self.data if all(item[k] == v for k,v in kwargs.items())]
>
> to return all matches
>
> Beware though that either of these will be slow if your list of dicts is large.
> If the list is large enough that this becomes slow, consider using a database (e.g. sqlite or other SQL DB) instead.

Thanks! Works perfectly.

> On 7 Dec 2020, 22:06 +0000, Larry Martell <larry.martell at gmail.com>, 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?
>
> --
>
> https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list