创建具有相同值的字典 [英] Creating a dictionary with same values

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

问题描述

假设我有字典 a = {} ,我想要这样一个结果

  value = 12 
a = {'a':value,'b':value,'f':value,'h':value,'p':value}

等等许多键:相同的值。现在我可以这样做了

  a.update({'a':value})
a .update({'b':value})

等等....
但是由于所有键的值是相同的,我们是否还有更多的pythonic方法呢?

解决方案

您可以使用 dict comprehensions (python 2.7 +):

 >>> v = 12 
>>>> d = {k:v for'abfhp'}
>>>>打印d
{'a':12,'h':12,'b':12,'p':12,'f':12}
pre>

Suppose I have dictionary a = {} and I want to have it a result like this

value = 12
a = {'a':value,'b':value,'f':value,'h':value,'p':value}

and so on for many keys:same value. Now of course I can do it like this

a.update({'a':value})
a.update({'b':value})

and so on.... but since the value is same for all the keys, don't we have a more pythonic approach to do this?

解决方案

You could use dict comprehensions (python 2.7+):

>>> v = 12
>>> d = {k:v for k in 'abfhp'}
>>> print d
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}

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

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