Python list of dictionaries search

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

    This looks to me the most pythonic way:

    people = [
    {'name': "Tom", 'age': 10},
    {'name': "Mark", 'age': 5},
    {'name': "Pam", 'age': 7}
    ]
    
    filter(lambda person: person['name'] == 'Pam', people)
    

    result (returned as a list in Python 2):

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

    Note: In Python 3, a filter object is returned. So the python3 solution would be:

    list(filter(lambda person: person['name'] == 'Pam', people))
    

提交回复
热议问题