如果密钥包含字符串列表中的字符串,则从字典列表中删除条目

时间:2018-05-25 21:14:55

标签: python list dictionary dictionary-comprehension

我有一个字典列表,每个都遵循完全相同的格式。我有一个字符串列表,表明应保留字典,以及一个字符串列表,表明应该删除字典。类似的东西:

d = [{"key1": 'x', "key2": 'y'},
     {"key1": 'x2', "key2": 'y2'},
     {"key1": 'x3', "key2": 'y3'}]

如果我要删除的字符串列表是

i = ['y2', 'y3']

最终名单将是

d = [{"key1": 'x', "key2": 'y'}]

我知道它应该是某种词典理解并尝试过

new_list = [a['key2'] for a in d if not any(j in a for j in i)]

如上所述,如果效率更高,我还会有一个字符串列表。

1 个答案:

答案 0 :(得分:2)

一个选项实际上比您当前的尝试更简单:

d = [{"key1": 'x', "key2": 'y'},
 {"key1": 'x2', "key2": 'y2'},
 {"key1": 'x3', "key2": 'y3'}]

i = ['y2', 'y3']
new_d = [c for c in d if c['key2'] not in i]

输出:

[{'key2': 'y', 'key1': 'x'}]