Last updated: Apr 9, 2024
Reading timeยท3 min
Use the dict.fromkeys()
method to set all dictionary values to 0.
The dict.fromkeys()
method creates a new dictionary with keys from the
provided iterable and values set to the supplied value.
my_dict = { 'bobby': 1, 'hadz': 2, 'com': 3, } my_dict = dict.fromkeys(my_dict, 0) print(my_dict) # ๐๏ธ {'bobby': 0, 'hadz': 0, 'com': 0}
We used the dict.fromkeys()
method to set all dictionary values to zero.
The dict.fromkeys() method takes an iterable and a value and creates a new dictionary with keys from the iterable and values set to the provided value.
# ๐๏ธ {'a': None, 'b': None, 'c': None} print(dict.fromkeys({'a': 'bobby', 'b': 'hadz', 'c': 'com'})) # ๐๏ธ {'a': 0, 'b': 0, 'c': 0} print(dict.fromkeys({'a': 'bobby', 'b': 'hadz', 'c': 'com'}, 0))
If you'd rather not change the dictionary in place, assign the output of calling
dict.fromkeys()
to a new variable.
my_dict = { 'bobby': 1, 'hadz': 2, 'com': 3, } new_dict = dict.fromkeys(my_dict, 0) print(new_dict) # ๐๏ธ {'bobby': 0, 'hadz': 0, 'com': 0}
Alternatively, you can use a dict comprehension.
my_dict = { 'bobby': 1, 'hadz': 2, 'com': 3, } my_dict = {key: 0 for key in my_dict} print(my_dict) # ๐๏ธ {'bobby': 0, 'hadz': 0, 'com': 0}
Dict comprehensions are very similar to list comprehensions.
On each iteration, we set the value of the key to zero and return the result.
Alternatively, you can use a simple for
loop.
This is a three-step process:
for
loop to iterate over the dictionary.my_dict = { 'bobby': 1, 'hadz': 2, 'com': 3, } for key in my_dict: my_dict[key] = 0 print(my_dict) # ๐๏ธ {'bobby': 0, 'hadz': 0, 'com': 0}
We used a for
loop to iterate over the dictionary.
On each iteration, we set the value of the current key to 0
.
If you'd rather not modify the original dictionary, declare a separate variable.
my_dict = { 'bobby': 1, 'hadz': 2, 'com': 3, } new_dict = {} for key in my_dict: new_dict[key] = 0 print(new_dict) # ๐๏ธ {'bobby': 0, 'hadz': 0, 'com': 0}
Instead of modifying the existing dictionary, we set all keys to 0 in a new dictionary.
I've also written an article on how to sum all values in a dictionary.
You can learn more about the related topics by checking out the following tutorials: