如果键和值与其他di不匹配,则从dict列表中删除dict

2024-10-02 20:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典列表,我想用其他字典的值来过滤它。你知道吗

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"}]

过滤器可以有多个键。可能的键有(姓名、姓氏、号码)。 基本上,我想要的是遍历dict列表,检查每个dict是否包含给定过滤器中的键,如果包含,检查键值是否匹配。如果他们没有,从dict列表中删除整个dict

最终列表不必是原始列表。它可以是一个新的列表。所以从原始列表中删除dicts不是强制性的。这些dict也可以复制到新的dict列表中。你知道吗


Tags: namecomnumber列表字典mailjohndict
2条回答

如果确定所有筛选字典的键都存在于其他字典中,则可以这样编写搜索(换句话说,缺少的键将被视为匹配):

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()}]

您可以使用列表理解:

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"
  }
]

相关问题 更多 >