Python字典创建语法 [英] Python dictionary creation syntax

查看:188
本文介绍了Python字典创建语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法来填充字典,以便您将多个键映射到相同的值,而不是说如下:

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

我正在考虑以下几点:

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

一个语法错误。



有没有一个相当简单的方法来做这个没有TOO很多的混淆? (我不打代码高尔夫球,但是我也不需要一遍又一遍地编写基本上相同的东西,但是代码高尔夫球的相关答案也是不错的,因为代码高尔夫是awesome =])。 / p>

修改



我可能选择了一个不好的例子。这是我想要做的:

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

我希望这样扩展到:

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

>编辑



我知道这是愚蠢的,完全不必要的,但我的目标是将这个声明放在一行上。这显然不应该限制任何回应和编写代码,只因为它符合1行是愚蠢的。但是我正在写一个模块级常数,如果它是一个班轮,这将是很好的。

解决方案

你可以把它周围:

 >>> d1 = {是:[1,2,3],否:[4]} 

然后转换该字典:

 >>> d2 = {value:键中的键,用于d1 [key]}中的值
>>>> d2
{1:'yes',2:'yes',3:'yes',4:'no'}


I'm wondering if there's any way to populate a dictionary such that you have multiple keys mapping to the same value that's less verbose than say:

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

I'm thinking something along the lines of:

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

which is obviously a syntax error.

Is there a reasonably simple method of doing this without TOO much obfuscation? (I'm not playing code golf, but I also don't need to write essentially the same thing over and over. However, any code-golf related answers would be appreciated as well since code-golf is awesome =]).

Edit:

I probably picked a bad example. This is what I'm trying to do:

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

What I would expect this to expand to is:

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

Edit->Edit:

I know this is stupid and totally unnecessary, but my goal is to make this declaration on a single line. This obviously shouldn't limit any responses and writing code just because it fits on 1 line is stupid. But I'm writing a module level constant dict that would be nice if it was a single liner.

解决方案

You could turn it around:

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

and then "invert" that dictionary:

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

这篇关于Python字典创建语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆