10
votes

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?

5

5 Answers

26
votes

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}
12
votes

How about creating a new dictionary with the keys that you want and a default value?. Check the fromkeys method.

>>> value=12
>>> a=dict.fromkeys(['a', 'b', 'f', 'h', 'p'], value)
>>> print a
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
2
votes
>>> a=dict(zip('abfhp',[12]*len('abfhp')))
>>> a
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
1
votes
a = dict()
for key in keys:
    a[key] = value
0
votes

As stummjr pointed out dictionary comprehension is useful to understand and use, especially since everything in python is a dicitonary.

Another way you could consider solving this problem is by lambda function.

makeDict = lambda keys, values: { k:v for k, v in zip(keys, values) }
makeDict( [1,2,3], list('abc') )
['a': 1, 'c': 3, 'b': 2]

Here is what makeDict looks rewritten as a regular function if this adds any clarity.

def makeDict(keys, values):
    return { k:v for k, v in zip(keys, values) }

Anyway, lambdas can be something fun to play around with, also this isn't the most robust example. There is a potential for loss of data using zip. Both sequences must be the same length for it to properly work. Python will iterate through till it has pairs to match up form both sequences. The following example the extra element in values shouldn't show up in the dictionary.

{ k:v for k, v in zip( list('abc'), [1,2,3,4]) }
['a': 1, 'c': 3, 'b': 2]