Python 字典创建语法

56 投票
8 回答
109513 浏览
提问于 2025-04-16 18:42

我在想有没有办法创建一个字典,让多个键指向同一个值,而不需要写得那么啰嗦,比如:

d = {1:'yes', 2:'yes', 3:'yes', 4:'no'}

我想的方式是这样的:

d = {*(1,2,3):'yes', 4:'no'}

但这显然是个语法错误。

有没有比较简单的方法可以做到这一点,而不会让代码看起来太复杂?(我不是在比拼代码的简洁性,但我也不想重复写几乎一样的东西。不过,如果有人给出与代码简洁性相关的答案,我也会很感激,因为代码简洁性真的很酷 =])。

编辑

我可能举了个不太好的例子。这是我想要做的:

d = {*('READY', 95): 'GPLR2_95', 'CHARGING': 'GPLR3_99', 'PROTECTION': 'GPLR3_100', 'CONNECTED': 'GPLR3_101', 'ERROR':'GPLR3_102'}

我希望这个能展开成:

d = {'READY':'GPLR2_95', 95: 'GPLR2_95', ...}

编辑->编辑

我知道这样做很傻,也完全没必要,但我的目标是把这个声明写成一行。显然,这不应该限制任何人的回答,单纯为了让代码在一行内而写代码是很傻的。不过,我正在写一个模块级的常量字典,如果能写成一行就太好了。

8 个回答

4

代码高尔夫?

yesindices = [1,2,3,22,34,33]
noindices = [4,8,9]
dict (zip(yesindices, ['yes' for i in yesindices]) + zip(noindices, ['no' for i in noindices]))

结果是

{1: 'yes', 2: 'yes', 3: 'yes', 4: 'no', 33: 'yes', 8: 'no', 9: 'no', 34: 'yes', 22: 'yes'}
9

这样怎么样:

501 $ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {"q":1}
>>> print a
{'q': 1}
>>> a["q"]
1
>>> a["r"] = a["s"] = a["t"] = 2
>>> a
{'q': 1, 's': 2, 'r': 2, 't': 2}
>>> 
87

你可以把它反过来:

>>> d1 = {"yes": [1,2,3], "no": [4]}

然后“反转”那个字典:

>>> d2 = {value:key for key in d1 for value in d1[key]}
>>> d2
{1: 'yes', 2: 'yes', 3: 'yes', 4: 'no'}

撰写回答