'Is there a way to store values in one dictionary key that has multiple optional values?

I want to do something like this:

my_dict = {
    ('a'|'b'|'c') : 1
}

Clearly, this doesn't work but I was wondering if there are ways around it that are the same or more efficient than writing each out:

my_dict = {
    'a' : 1,
    'b' : 1,
    'c' : 1
}

Any ideas?



Solution 1:[1]

You can create a dictionary with multiple keys all mapping to the same value using dict.fromkeys.

The first argument is a sequence of keys; the second argument is the value.

>>> dict.fromkeys('abc', 1)
{'a': 1, 'b': 1, 'c': 1}

'abc' works as a sequence of keys because in this case all your keys are strings of one character. More generally you can use a tuple or a list:

>>> dict.fromkeys(['a','b','c'], 1)
{'a': 1, 'b': 1, 'c': 1}

(N.B. creating a dict this way might cause problems if your value was mutable, since all the keys would reference the same value object.)

Solution 2:[2]

Create a dictionary with 3 keys, all with the value 1:

x = ('a', 'b', 'c')
y = 1

thisdict = dict.fromkeys(x, y)

print(thisdict)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 khelwood
Solution 2 BETTACHE-KARIM