我想在列表中输出所有字典项,这些列表项对其中一个键包含部分查询。
考虑到this question,我希望从以下列表中实现类似的目的:
people = [
{"name": "Pamela","age": 9}
{"name": "Tom","age": 10},{"name": "Mark","age": 5},{"name": "Pam","age": 7}
]
搜索"Pam"
,我想获得这两个条目:
{"name": "Pamela","age": 9},"age": 7}
由于我想根据用户偏好在字典中搜索不同的键,因此我认为这是在上述线程中找到的最佳解决方案:
def search(db,key,value):
for item in db:
if value in item[key]: # This is the line i'm having trouble with
return item
但是,命令print(search(people,'name','Pam'))
仅输出
{"name": "Pam","age": 7}