+1 vote
in Programming Languages by (7.9k 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

0 votes
by (15.3k points)

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}

...