假设我有一个字典列表,所有的字典都有相同的键。列表中这样一个字典的实例可能看起来像:
dict = {"Height": 6.0, "Weight": 201.5, "Name": "John", "Status": "Married"}
只给定几个(键,值)对,我想提取所有满足这些对的字典。例如,如果我有
attributes = {"Height": 5.5, "Name": "John"}
我想提取高度值大于等于5.5且名称值为John的所有字典。
我能够编写可以满足一个或另一个的代码,但是处理混合类型(float和string)让我感到困惑,所以我的and操作符被混淆了。例如,我的代码中的问题部分是:
for option in attributes.keys():
if dict[option] == attributes[option] and dict[option] >= attributes[option]
print dict
如果你有多个不同的条件,你必须做所有的,但不是使用and
,你可以使用all
内置函数和过滤字典的函数,然后在列表推导或filter
函数中使用它,以获得期望的字典。
from operator import itemgetter
option1, option2, option3 = itemgetter(key1, key2, key3)(attributes)
def filter_func(temp_dict):
# key1, key2, key3 have been defined already (keys in attributes)
val1, val2, val3 = itemgetter(key1, key2, key3)(temp_dict)
return all(option1 == val1, option2 => val2, option3 => val3)
filtered_result = filter(filter_func, list_of_dictionaries)
还请注意,如果列表的字典可能没有所有指定的键,那么itemgetter
可能会引发KeyError
来获取,您可以通过向其传递默认值来使用dict.get
属性(根据您的需要)。
例如val3
你可以使用temp_dict.get(key3, 0)