Python list of dictionaries search

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

    You can use a generator expression:

    >>> dicts = [
    ...     { "name": "Tom", "age": 10 },
    ...     { "name": "Mark", "age": 5 },
    ...     { "name": "Pam", "age": 7 },
    ...     { "name": "Dick", "age": 12 }
    ... ]
    
    >>> next(item for item in dicts if item["name"] == "Pam")
    {'age': 7, 'name': 'Pam'}
    

    If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:

    next((item for item in dicts if item["name"] == "Pam"), None)
    

    And to find the index of the item, rather than the item itself, you can enumerate() the list:

    next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
    

提交回复
热议问题