我有一个函数可以根据某些键的值过滤字典列表,就像SELECT * WHERE xxxSQL 中的查询一样list_of_dict = [{'key1':val, 'key2':val},{'key1':val, 'key2':val},...]def filter_list(list_of_dict, key1, key2=None): if key2: filtered_list = [i for i in list_of_dict if i['key1']==key1 and i['key2']==key2] else: filtered_list = [i for i in list_of_dict if i['key1']==key1]但是当我有更多的键作为函数的参数时,if ...else...可能会很长。有没有更Pythonic的方法来做到这一点?
1 回答
MM们
TA贡献1886条经验 获得超2个赞
如果您有大量或可变数量的键,则可以使用all循环遍历它们。下面是一个示例,其中键值作为关键字参数提供:
def filter_dicts(dicts, **keys):
return [
d for d in dicts
if all(d[k] == v for k, v in keys.items())
]
正如 @juanpa.arrivillaga 指出的,dict_items对象在许多方面的行为类似于集合,因此您可以选择过滤具有keys子集的字典:
def filter_dicts(dicts, **keys):
return [d for d in dicts if keys.items() <= d.items()]
例子:
>>> dicts = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}]
>>> filter_dicts(dicts, x=1)
[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}]
>>> filter_dicts(dicts, x=1, y=2)
[{'x': 1, 'y': 2}]
>>> filter_dicts(dicts, y=3)
[{'x': 1, 'y': 3}]
添加回答
举报
0/150
提交
取消