我有一个字典列表,如果2个键的值中的2个每个都有一个已定义的字符串,我想要过滤这些字典
例如,在下面的列表中过滤(A = BBB和D = EEE)......
[{A:BBB, C:DDD, D:EEE,...}, {A:BBB, C:DDD, D:ESS,...},{A:BBB, C:ASD, D:EEE,...},{C:ASD, D:EEE,...},...]
输出
[{A:BBB, C:DDD, D:EEE,...},{A:BBB, C:ASD, D:EEE,...},...]
任何帮助将不胜感激!
答案 0 :(得分:4)
试试这个,它是一个使用列表推导的单行:
# input data
lst = [{'A':'BBB', 'C':'DDD', 'D':'EEE'},
{'A':'BBB', 'C':'DDD', 'D':'ESS'},
{'A':'BBB', 'C':'ASD', 'D':'EEE'},
{'C':'ASD', 'D':'EEE'}]
# list of filters
flt = [('A', 'BBB'), ('D', 'EEE')]
# a list comprehension + all() will do the trick
[x for x in lst if all(x.get(k, None) == v for k, v in flt)]
=> [{'A': 'BBB', 'C': 'DDD', 'D': 'EEE'}, {'A': 'BBB', 'C': 'ASD', 'D': 'EEE'}]
这种方法的好处是你可以根据需要在过滤器中声明尽可能多的键/值对,无论如何它都可以工作。
答案 1 :(得分:0)
result = []
for i in lst:
if i['A'] == "BBB" and i['D'] == "EEE":
result.append(i)
答案 2 :(得分:0)
l = [{'A': 'BBB', 'C': 'DDD', 'D': 'EEE'}, {'A': 'BBB', 'C': 'DDD', 'D': 'ESS'},
{'A': 'BBB', 'C': 'ASD', 'D': 'EEE'}, {'C': 'ASD', 'D': 'EEE'}]
filterd = {'D': 'EEE', 'A': 'BBB'}
[x for x in l if x.viewvalues() >= filterd.viewvalues()]
[{'A': 'BBB', 'C': 'DDD', 'D': 'EEE'}, {'A': 'BBB', 'C': 'ASD', 'D': 'EEE'}]
答案 3 :(得分:-2)
output = [d for d in list_of_dicts
if not (d['A'] == 'BBB' and d['D'] == 'EEE')]