我有一个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}
]
我怎样才能做到这一点?
答案 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())]