Simultaneously replacing all values of a dictionary to zero python
Question:
I have a very large dictionary, maybe about 10,000 keys/values
and I want to simultaneously change all values to 0
. I am aware that I can loop through and set all the values to 0
but it take forever. Is there anyway that I can simultaneously set all values to 0
?
Looping method, very slow:
# example dictionary
a = {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'h': 1, 'k': 1,
'j': 1, 'm': 1, 'l': 1, 'o': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 'r': 1, 'u': 1,
't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1}
for key, value in a.items():
a[key] = 0
Output:
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0,
'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0,
't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
Answers:
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
To expand on @Daniel Roseman answer a=a.fromkeys(d,0)
is functionaly the same and a bit faster. Also if you plan to do this frequently save=dict.fromkeys(a,0)
and then call a=save.copy()
which is faster in some cases(large dicts)
I have a very large dictionary, maybe about 10,000 keys/values
and I want to simultaneously change all values to 0
. I am aware that I can loop through and set all the values to 0
but it take forever. Is there anyway that I can simultaneously set all values to 0
?
Looping method, very slow:
# example dictionary
a = {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'h': 1, 'k': 1,
'j': 1, 'm': 1, 'l': 1, 'o': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 'r': 1, 'u': 1,
't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1}
for key, value in a.items():
a[key] = 0
Output:
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0,
'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0,
't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
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
To expand on @Daniel Roseman answer a=a.fromkeys(d,0)
is functionaly the same and a bit faster. Also if you plan to do this frequently save=dict.fromkeys(a,0)
and then call a=save.copy()
which is faster in some cases(large dicts)