【问题标题】:Grabbing a dictionary given just a few keys and values仅给定几个键和值就获取字典
【发布时间】:2017-01-23 17:52:17
【问题描述】:

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

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 

【问题讨论】:

  • 这不是一个非常明确的问题。例如,代码应该如何知道 Height 键是最小值 - 而不是要搜索的确切值,例如 Name 键?

标签: python-2.7 dictionary types


【解决方案1】:

如果您有多个不同的条件,则必须全部执行,但您可以使用 all 内置函数和过滤字典的函数,而不是使用 and,然后在列表理解中使用它或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)

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多