轻松过滤的最佳包装是什么?像django-filter,但我在django对象之外。
例如
>>dict = {
{'name':'apple','amount':10},
{'name':'apple','amount':5},
{'name':'banana','amount':10},
{'name':'green-apple','amount':20},
}
>>filter(dict,name='apple')
{'name':'apple','amount':10},{'name':'apple','amount':10}
>>filter(dict,name='apple',amount=10)
{'name':'apple','amount':10}
>>filter(dict,amount_gt=5)
{'name':'apple','amount':10},{'name':'banana','amount':10}
>>filter(dict,amount_gte=5)
{'name':'apple','amount':10},{'name':'apple','amount':5},{'name':'banana','amount':10}
>>filter(dict,amount_lt=10)
{'name':'apple','amount':5}
>>filter(dict,name_regex=".*apple")
{'name':'apple','amount':5},{'name':'apple','amount':10},{'name':'green-apple','amount':20}
答案 0 :(得分:2)
您可以使用以下功能:
def filter_dicts(dict_list, **kwargs):
for item in dict_list:
if all(item[k] == v for k, v in kwargs.items()):
yield item
用法:
dict_list = [
{"name": "apple", "amount": 10},
{"name": "apple", "amount": 15},
{"name": "orange", "amount": 5}
]
for d in filter_dicts(dict_list, name="apple", amount=10):
print(d)
或者,您也可以这样做:
filtered_dicts = [item for item in dict_list if item["amount"] > 10 and item["name"] == "apple"]
答案 1 :(得分:0)
您可以使用items
将dict转换为列表
并在该列表上使用过滤器,即
filter(lambda x : x[0] == 'amount', dict.items())
你也可以将它转换回来