创建具有相同值的字典 [英] Creating a dictionary with same values
本文介绍了创建具有相同值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
pre>
>>>> d = {k:v for'abfhp'}
>>>>打印d
{'a':12,'h':12,'b':12,'p':12,'f':12}
Suppose I have dictionary
a = {}
and I want to have it a result like thisvalue = 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 thisa.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屋!
查看全文