I want to know if there is a way to have a default value in a dictionary (without using the get function), so that:
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
Of course, the code above wouldn't work in Python, and I have serious doubt it is even possible.
I Know that by using get I could do this easily, however I'm still curious if there is any other way (just for curiosity).
2 Answers 2
You can use a 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"])
Comments
Check out the collections.defaultdict type (https://docs.python.org/3/library/collections.html#collections.defaultdict):
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
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'])