简体   繁体   中英

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?

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}

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

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

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

thisdict = dict.fromkeys(x, y)

print(thisdict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM