Python中是否有一种在字典中设置默认值的方式?

4

我想知道在字典中是否有一种方式可以设置默认值(而不使用get函数),使得:

dict colors = {
"Black":(0, 0, 0),
"White":(255, 255, 255),
default:(100, 100, 100)
};

paint(colors["Blue"]);  # Paints the default value (Grey) onto the screen


当然,上述代码在Python中无法运行,我严重怀疑这是不可能的。
我知道通过使用“get”函数可以轻松实现此操作,但我仍然好奇是否有其他方法(只是出于好奇)。
2个回答

8
你可以使用一个defaultdict
from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100))

colors["Black"] = (0, 0, 0),
colors["White"] = (255, 255, 255)

# Prints (0, 0, 0), because "Black" is mapped to (0, 0, 0) in the dictionary.
print(colors["Black"]) 

# Prints (100, 100, 100), because "Blue" is not a key in the dictionary.
print(colors["Blue"])

6

请查看 collections.defaultdict 类型 (https://docs.python.org/3/library/collections.html#collections.defaultdict):

第一个参数提供了 default_factory 属性的初始值,默认为 None。所有剩余的参数都被视为传递给字典构造函数的参数,包括关键字参数。

您的代码应该像这样使用它:

from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100), {
    "Black":(0, 0, 0),
    "White":(255, 255, 255),
})

print(colors['Blue'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接