首先,我们可以有一个简单的脚本,它只使用内置的python filter method,这可能已经足够了:
fl = list(filter(lambda x: x['first'] == 'Christian', dictlist))
# you can't use `.property` because this is a dictionary, not a object
fl[0]['last']
# returns Doppler
我知道你的例子是一个 Django 代码,所以如果你想让它更加动态,以便你能够通过字典中的任何键进行过滤:
def dict_filter(dictlist: list, key: str, value: str) -> list:
return list(filter(lambda x: x.get(key) == value, dictlist))
dict_filter(dictlist, 'first', 'Christian')
# similar to django's filter method returns a queryset, this returns a list:
# [{'first': 'Christian', 'last': 'Doppler'}]
dict_filter(dictlist, 'last', 'Doppler')
# returns [{'first': 'Christian', 'last': 'Doppler'}]
dict_filter(dictlist, 'last', 'notfound')
# returns []
以及使用python filter method 来创建与Django 的QuerySet.get 方法类似的函数的示例:
def dict_get(dictlist: list, key: str, value: str) -> list:
ret = list(filter(lambda x: x.get(key) == value, dictlist))
if len(ret) == 0:
raise Exception('Not Found')
if len(ret) > 1:
raise Exception(f'Found more than 1 object with {key}={value}')
return ret[0]
dict_get(dictlist, 'first', 'Christian')
# returns {'first': 'Christian', 'last': 'Doppler'}
dict_get(dictlist, 'first', 'Christians')
# raises Exception: Not Found
dict_get(dictlist, 'first', 'James')
# raises Exception: Found more than 1 object with first=James
希望对你有帮助!