Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously replacing all values of a dictionary to zero python

People also ask

How do you update all values in a dictionary?

Python Dictionary update all values We can easily do this by using update() function. The python update() method updates the dictionary with the key and value pairs. It inserts a key/value if it is not present. It updates the key/value if it is already present in the dictionary.

Can we use Replace in dictionary Python?

To replace all the multiple substrings in a string based on a dictionary. We can loop over all the key-value pairs in a dictionary and for each key-value pair, replace all the occurrences of “key” substring with “value” substring in the original string using the regex.

Can you set multiple values to the same key in dictionary Python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.


You want dict.fromkeys():

a = dict.fromkeys(a, 0)

Thanks @akaRem for his comment :)

a = dict.fromkeys( a.iterkeys(), 0 )

Be warned, if the order of your keys matter the solution may not be suitable as it seems to reorder.

To stop this from happening use list comprehension:

aDictionary =  { x:0 for x in aDictionary}

Note: It's only 2.7.x and 2.x exclusive