只需几个键和值即可抓取字典

时间:2016-09-15 16:01:03

标签: python-2.7 dictionary types

假设我有一个词典列表,所有词典都有相同的键。列表中此类字典的实例可能如下所示:

dict = {"Height": 6.0, "Weight": 201.5, "Name": "John", "Status": "Married"}

只给出几个(键,值)对,我想提取满足这些对的所有词典。例如,如果我有

attributes = {"Height": 5.5, "Name": "John"}

我想提取高度值大于或等于5.5的所有字典,其名称值为John。

我能够编写能够满足一个或另一个的代码,但处理混合类型(浮点数和字符串)会让我失望,所以我的AND运算符让我感到困惑。例如,我的代码的问题部分是:

for option in attributes.keys():
    if dict[option] == attributes[option] and dict[option] >= attributes[option]
    print dict 

1 个答案:

答案 0 :(得分:0)

如果您有多种不同的条件,则必须执行所有这些操作,但是您可以使用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),您可以使用Redirect 301 /old/oldfile.html /new