Python list of dictionaries search

后端 未结 21 2455
-上瘾入骨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:10

    You can achieve this with the usage of filter and next methods in Python.

    filter method filters the given sequence and returns an iterator. next method accepts an iterator and returns the next element in the list.

    So you can find the element by,

    my_dict = [
        {"name": "Tom", "age": 10},
        {"name": "Mark", "age": 5},
        {"name": "Pam", "age": 7}
    ]
    
    next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)
    

    and the output is,

    {'name': 'Pam', 'age': 7}
    

    Note: The above code will return None incase if the name we are searching is not found.

提交回复
热议问题