11

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?

NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53

5 Answers5

30

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}
Valdir Stumm Junior
  • 4,568
  • 1
  • 23
  • 31
  • How would you extend this to change the value in a dict that looks like `{'a': {'b': v}, {'c': v}, {'d': v}, 'e': {'f': v}, {'g': v}}`? – Vishal Jul 29 '17 at 07:39
15

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}
Savir
  • 17,568
  • 15
  • 82
  • 136
  • 1
    This is ok as long as value isn't mutable. Otherwise you will be in for interesting bugs – John La Rooy Aug 15 '12 at 21:44
  • @gnibbler: Correct, but the user said "since the value is same for all the keys"... But I understand what you mean... I've had some funky issues with things like >>> i=1 >>> [i+1]*5 (gives [2, 2, 2, 2, 2], not [2, 3, 4, 5, 6])... – Savir Aug 15 '12 at 21:49
2
>>> a=dict(zip('abfhp',[12]*len('abfhp')))
>>> a
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1
a = dict()
for key in keys:
    a[key] = value
rsegal
  • 401
  • 3
  • 11
0

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]
Dan
  • 1,179
  • 2
  • 10
  • 18