Python list of dictionaries search

后端 未结 21 2047
-上瘾入骨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))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:14

    You have to go through all elements of the list. There is not a shortcut!

    Unless somewhere else you keep a dictionary of the names pointing to the items of the list, but then you have to take care of the consequences of popping an element from your list.

    0 讨论(0)
  • 2020-11-22 10:15

    To add just a tiny bit to @FrédéricHamidi.

    In case you are not sure a key is in the the list of dicts, something like this would help:

    next((item for item in dicts if item.get("name") and item["name"] == "Pam"), None)
    
    0 讨论(0)
  • 2020-11-22 10:15
    names = [{'name':'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
    resultlist = [d    for d in names     if d.get('name', '') == 'Pam']
    first_result = resultlist[0]
    

    This is one way...

    0 讨论(0)
  • 2020-11-22 10:15

    Simply using list comprehension:

    [i for i in dct if i['name'] == 'Pam'][0]
    

    Sample code:

    dct = [
        {'name': 'Tom', 'age': 10},
        {'name': 'Mark', 'age': 5},
        {'name': 'Pam', 'age': 7}
    ]
    
    print([i for i in dct if i['name'] == 'Pam'][0])
    
    > {'age': 7, 'name': 'Pam'}
    
    0 讨论(0)
提交回复
热议问题