+2 votes
in Programming Languages by (77.7k points)
I created a dictionary and want to set all the key's values to 0. How can I initialize in Pythonic style?

1 Answer

+1 vote
by (355k points)
selected by
 
Best answer

You can use fromkeys() function of the dict module. Check the following example where I have initialized all the key's values to 0.

>>> keys=['a','b','c','d','e']
>>> dd1=dict.fromkeys(keys,0)
>>> dd1
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}

You can also use 'for' loop for the initialization. Here is an example

>>> keys=['a','b','c','d','e']
>>> dd={}
>>> for k in keys:
...     dd[k]=0
...
>>> dd
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}


...