如何在Dicts中实现基本搜索

时间:2017-02-27 19:50:04

标签: python algorithm dictionary search

我有一个dicts列表如下:

[
    {"name":"Some", "surname":"Body","age":22},
    {"name":"Some", "surname":"One", "age":23},
    {"name":"Any", "surname":"Body", "age":20}
]

我需要一个能够搜索dicts的函数,如下所示:

def search(data:dict, **kwargs):
    pass

search(mydict, surname="Body")
[
    {"name":"Some", "surname":"Body","age":22},
    {"name":"Any", "surname":"Body", "age":20}
]

search(mydict, name="Some")
[
    {"name":"Some", "surname":"Body","age":22},
    {"name":"Some", "surname":"One", "age":23}
]

search(mydict, age=23)
[
    {"name":"Any", "surname":"Body", "age":20}
]

我怎样才能做到这一点?

环境

  • Python 3.5

1 个答案:

答案 0 :(得分:1)

以下是使用all测试包含kwargs中确切键值的词典的一种方法:

lst = [
    {"name":"Some", "surname":"Body","age":22},
    {"name":"Some", "surname":"One", "age":23},
    {"name":"Any", "surname":"Body", "age":20}
]


def search(data:dict, **kwargs):
    return [d for d in data if all(d[k]==v for k, v in kwargs.items())] 

print(search(lst, surname="Body", age=22))
# [{'name': 'Some', 'age': 22, 'surname': 'Body'}]

您可以使用dict的.get方法处理缺失的密钥,然后默认传递sentinel对象:

def search(data:dict, **kwargs):
    return [d for d in data if all(d.get(k, object())==v for k, v in kwargs.items())]