[英]Is there a way to have a default value inside a dictionary in Python?
I wnat to know if there is a way to have a default value in a dictionary (without using the get function), so that:我想知道是否有办法在字典中设置默认值(不使用 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
You can use a defaultdict<\/code> .
您可以使用
defaultdict<\/code> 。
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(d["Blue"])
Check out the collections.defaultdict type ( https:\/\/docs.python.org\/3\/library\/collections.html#collections.defaultdict<\/a> ):查看 collections.defaultdict 类型( https:\/\/docs.python.org\/3\/library\/collections.html#collections.defaultdict<\/a> ):
<\/blockquote>Your code would use it like this:您的代码将像这样使用它:
from collections import defaultdict colors = defaultdict(lambda: (100, 100, 100), { "Black":(0, 0, 0), "White":(255, 255, 255), }) print(colors['Blue'])<\/code><\/pre>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.