我有一个函数可以根据某些键的值过滤字典列表,就像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的方法来做到这一点?
MM们
相关分类