我有一个字典列表,我想用其他字典中的值过滤它。
orig_list = [{"name":"Peter","last_name":"Wick","mail":"Peter@mail.com","number":"111"},
{"name":"John","last_name":"Hen","mail":"John@mail.com","number":"222"},
{"name":"Jack","last_name":"Malm","mail":"Jack@mail.com","number":"542"},
{"name":"Anna","last_name":"Hedge","mail":"Anna@mail.com"},
{"name":"Peter","last_name":"Roesner","mail":"Peter2@mail.com","number":"445"},
{"name":"Tino","last_name":"Tes","mail":"Tino@mail.com","number":"985"},]
预期结果示例1:
filter = {"name":"Peter"}
orig_list[{"name":"Peter","last_name":"Wick","mail":"Peter@mail.com","number":"111"},
{"name":"Peter","last_name":"Roesner","mail":"Peter2@mail.com","number":"445"}]
预期结果示例2:
filter = {"name":"Peter","number":"445"}
orig_list[
{"name":"Peter","last_name":"Roesner","mail":"Peter2@mail.com","number":"445"}]
过滤器可以具有多个键。可能的键是(name,last_name,number)。 基本上,我想要的是浏览字典列表,并检查每个字典是否该字典包含给定过滤器中的键,如果包含,则检查键值是否匹配。如果没有,请从字典列表中删除整个字典。
最终列表不必是orig_list。它可以是一个新列表。因此,从orig_list中删除字典不是强制性的。也可以将字典复制到新的字典列表中。
答案 0 :(得分:3)
您可以使用列表理解:
orig_list = [{"name":"Peter","last_name":"Wick","mail":"Peter@mail.com","number":"111"},
{"name":"John","last_name":"Hen","mail":"John@mail.com","number":"222"},
{"name":"Jack","last_name":"Malm","mail":"Jack@mail.com","number":"542"},
{"name":"Anna","last_name":"Hedge","mail":"Anna@mail.com"},
{"name":"Peter","last_name":"Roesner","mail":"Peter2@mail.com","number":"445"},
{"name":"Tino","last_name":"Tes","mail":"Tino@mail.com","number":"985"},]
filter_by = {"name":"Peter"}
result = [dic for dic in orig_list if all(key in dic and dic[key] == val for key, val in filter_by.items())]
print(result)
输出:
[
{
"name": "Peter",
"last_name": "Wick",
"mail": "Peter@mail.com",
"number": "111"
},
{
"name": "Peter",
"last_name": "Roesner",
"mail": "Peter2@mail.com",
"number": "445"
}
]
对于filter_by = {"name":"Peter","number":"445"}
,您将获得:
[
{
"name": "Peter",
"last_name": "Roesner",
"mail": "Peter2@mail.com",
"number": "445"
}
]
答案 1 :(得分:0)
如果您确定所有字典词典的键都存在于其他词典中,则可以这样编写搜索(换句话说,缺少的键将被视为匹配):
filterDict = {"name":"Peter"}
result = [ d for d in orig_list if {**d,**filterDict} == d ]
如果缺少的键不匹配,则可以执行以下操作:
result = [d for d in orig_list if {*filterDict.items()}<={*d.items()}]