Skip to main content

How to Set All Dictionary Values to Zero in Python

This guide explains how to set all values in a Python dictionary to zero (0). We'll cover in-place modification using loops and the more concise and efficient dictionary comprehension and dict.fromkeys() methods.

The dict.fromkeys() method is the most concise and efficient way to create a new dictionary with all values set to 0, without modifying the original:

my_dict = {
'tutorial': 1,
'reference': 2,
'com': 3,
}

new_dict = dict.fromkeys(my_dict, 0) # Creates a NEW dictionary
print(new_dict) # Output: {'tutorial': 0, 'reference': 0, 'com': 0}
print(my_dict) # Output: {'tutorial': 1, 'reference': 2, 'com': 3} (original is unchanged)
  • dict.fromkeys(iterable, value) creates a new dictionary.
    • iterable: The keys for the new dictionary are taken from this iterable (in this case, the keys of my_dict).
    • value: All keys in the new dictionary will be assigned this value (0 in this case).
  • The result will be a new dictionary.
  • The original dictionary my_dict is not modified.

Using a Dictionary Comprehension (Creating a new dictionary)

Dictionary comprehensions provide another concise way to create a new dictionary with all values set to 0:

my_dict = {
'tutorial': 1,
'reference': 2,
'com': 3,
}

new_dict = {key: 0 for key in my_dict} # Creates a NEW dictionary
print(new_dict) # Output: {'tutorial': 0, 'reference': 0, 'com': 0}
print(my_dict) # Output: {'tutorial': 1, 'reference': 2, 'com': 3} (original is unchanged)
  • Creates a new dictionary, without altering the original.

Using a for Loop (Modifying in-place)

If you want to modify the original dictionary in place, use a for loop:

my_dict = {
'tutorial': 1,
'reference': 2,
'com': 3,
}

for key in my_dict:
my_dict[key] = 0 # Modify the ORIGINAL dictionary

print(my_dict) # Output: {'tutorial': 0, 'reference': 0, 'com': 0}
  • This iterates directly over the keys of the dictionary. for key in my_dict is equivalent to for key in my_dict.keys().
  • my_dict[key] = 0 sets the value associated with each key to 0, directly modifying the original my_dict.