Skip to main content
 首页 » 编程设计

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

2025年05月04日18mfryf

我知道有 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)