根据值列表中的元素是否存在过滤 python 字典的有效方法是什么?
What's the efficient way to filter a python dictionary based on whether an element in a value list exists?
我有一个定义如下的字典 (table):
table = {"id": [1, 2, 3]}, {"file": ['good1.txt', 'bad2.txt', 'good3.txt']}
我有一份应该删除的不良候选人名单:
to_exclude = ['bad0.txt', 'bad1.txt', 'bad2.txt']
我希望根据我的 table 行中的文件是否可以在 to_exclude 中找到来过滤 table。
filtered = {"id": [1, 2]}, {"file": ['good1.txt', 'good3.txt']}
我想我可以使用 for 循环逐一检查条目,但我想知道解决此问题的最 python 有效方式是什么。
有人可以提供一些指导吗?谢谢
我假设您写错了数据结构。你有一套两本字典,这是不可能的。 (字典不可散列)。我希望你的实际数据是:
data = {"id": [1, 2, 3], "file": [.......]}
一个有两个键的字典。
所以对我来说,最简单的是:
# Create a set for faster testing
to_exclude_set = set(to_exclude)
# Create (id, file) pairs for the pairs we want to keep
pairs = [(id, file) for id, file in zip(data["id"], data["file"])
if file not in to_exclude_set]
# Recreate the data structure
result = { 'id': [_ for id, _ in pairs],
'file': [_ for _, file in pairs] }
我有一个定义如下的字典 (table):
table = {"id": [1, 2, 3]}, {"file": ['good1.txt', 'bad2.txt', 'good3.txt']}
我有一份应该删除的不良候选人名单:
to_exclude = ['bad0.txt', 'bad1.txt', 'bad2.txt']
我希望根据我的 table 行中的文件是否可以在 to_exclude 中找到来过滤 table。
filtered = {"id": [1, 2]}, {"file": ['good1.txt', 'good3.txt']}
我想我可以使用 for 循环逐一检查条目,但我想知道解决此问题的最 python 有效方式是什么。
有人可以提供一些指导吗?谢谢
我假设您写错了数据结构。你有一套两本字典,这是不可能的。 (字典不可散列)。我希望你的实际数据是:
data = {"id": [1, 2, 3], "file": [.......]}
一个有两个键的字典。
所以对我来说,最简单的是:
# Create a set for faster testing
to_exclude_set = set(to_exclude)
# Create (id, file) pairs for the pairs we want to keep
pairs = [(id, file) for id, file in zip(data["id"], data["file"])
if file not in to_exclude_set]
# Recreate the data structure
result = { 'id': [_ for id, _ in pairs],
'file': [_ for _, file in pairs] }