简体   繁体   English

有没有一种方法可以将值存储在一个具有多个可选值的字典键中?

[英]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 .您可以使用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. 'abc'用作一系列键,因为在这种情况下,您的所有键都是一个字符的字符串。 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.) (注意,如果您的值是可变的,以这种方式创建字典可能会导致问题,因为所有键都将引用相同的值 object。)

Create a dictionary with 3 keys, all with the value 1:创建一个包含 3 个键的字典,所有键的值为 1:

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

thisdict = dict.fromkeys(x, y)

print(thisdict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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