5

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).

asked Feb 6, 2022 at 2:45

2 Answers 2

9

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"])
answered Feb 6, 2022 at 2:49
Sign up to request clarification or add additional context in comments.

Comments

7

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'])
answered Feb 6, 2022 at 2:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.