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?
CodePudding user response:
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.)
CodePudding user response:
Create a dictionary with 3 keys, all with the value 1:
x = ('a', 'b', 'c')
y = 1
thisdict = dict.fromkeys(x, y)
print(thisdict)