python - 过滤字典列表以始终返回单个字典,给定要查找的默认键值

标签 python list dictionary

我知道有 1001 种方法可以解决这个问题,我要求社区了解什么是最 Pythonic 的方法。

假设我有一个采用以下格式的字典列表:

colours = [{"color": "green", "owner": "Mark"},
           {"color": "blue", "owner": "Luke"},
           {"color": "red", "owner": "John"}]

忽略列表应该是字典的字典这个明显的事实,我想从列表中检索单个字典,给定字典中 color 键的用户输入,但是使用如果颜色不匹配,则为默认值(在本例中假设为“绿色”)。

因此我正在寻找一个函数:

def get_with_default(colour, colours, default):

给定颜色列表将返回:

>>> get_with_default("blue", colours, "green") # Valid dictionary
{"color": "blue", "owner": "Luke"}
>>> get_with_default("black", colours, "green") # Colour doesn't exist
{"color": "green", "owner": "Mark"}

更新(感谢 Martijn),默认值将被硬编码并已知在列表中,但是该字典中的其他键/值对是未知/动态(所以我知道“绿色”是字典中的关键字,但我知道在这种简化情况下谁“拥有”绿色

最佳答案

next()是实现这一点的最pythonic函数:

def get_with_default(colour, colours, default):
    search = (d for d in colours if d['color'] in (colour, default))
    match_or_default = next(search)
    if match_or_default['color'] != default or default == colour:
        return match_or_default
    return next(search, match_or_default)

next() 循环遍历第一个参数,直到产生结果,然后返回该结果。如果第一个参数耗尽,将引发 StopIteration,除非给出第二个参数(默认值),在这种情况下返回该值而不是引发异常。

通过为它提供一个体现搜索的生成器表达式,您可以高效地扫描 colours 列表以找到第一个匹配项。如果这是默认设置,那么我们将继续扫描,直到找到其他 匹配项,或到达列表末尾。

演示:

>>> get_with_default("blue", colours, "green")
{'color': 'blue', 'owner': 'Luke'}
>>> get_with_default("black", colours, "green")
{'color': 'green', 'owner': 'Mark'}

上述方法非常有效,因为它只需要扫描输入列表一次,并且一旦找到匹配就停止扫描。

请注意,如果默认值也不存在,此函数将引发 StopIteration:

>>> get_with_default("black", colours, "purple")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_with_default
StopIteration

在这种情况下,您也可以通过为第一个 next() 调用提供默认返回值来返回 None:

match_or_default = next(search, None)

关于python - 过滤字典列表以始终返回单个字典,给定要查找的默认键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17786675/

相关文章:

java - 使用包含括号的列表将特定括号(左括号、右括号)存储在堆栈中

java - 使用比较器实例化 TreeMap,该比较器应该能够访问所述 TreeMap

javascript - 从数组映射返回对象

python - 创建具有图像识别功能的独立项目

python - 如何在selenium中使用python webdriver从csv文件调用多个数据

python - 在 Python 3 中从推文中解码表情符号

python - Azure 机器学习工作区笔记本的版本控制

python - 考虑顺序如何检查列表(字符串)是否包含另一个列表(字符串)

python - 如何根据某些文本条件对元组列表进行分组/存储?

python - 将 dict 值四舍五入为 2 位小数