Python list of dictionaries search

后端 未结 21 2297
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:41

Assume I have this:

[
{\"name\": \"Tom\", \"age\": 10},
{\"name\": \"Mark\", \"age\": 5},
{\"name\": \"Pam\", \"age\": 7}
]

and by searchin

21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 10:00

    Most (if not all) implementations proposed here have two flaws:

    • They assume only one key to be passed for searching, while it may be interesting to have more for complex dict
    • They assume all keys passed for searching exist in the dicts, hence they don't deal correctly with KeyError occuring when it is not.

    An updated proposition:

    def find_first_in_list(objects, **kwargs):
        return next((obj for obj in objects if
                     len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
                     all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
                    None)
    

    Maybe not the most pythonic, but at least a bit more failsafe.

    Usage:

    >>> obj1 = find_first_in_list(list_of_dict, name='Pam', age=7)
    >>> obj2 = find_first_in_list(list_of_dict, name='Pam', age=27)
    >>> obj3 = find_first_in_list(list_of_dict, name='Pam', address='nowhere')
    >>> 
    >>> print(obj1, obj2, obj3)
    {"name": "Pam", "age": 7}, None, {"name": "Pam", "age": 7}
    

    The gist.

提交回复
热议问题