Replacing all dictionary values ​​with zero python at the same time

I have a very large dictionary, maybe around 10,000 keys/values , and I want to change all the values ​​to 0 at the same time. I know that I can execute a loop and set all the values ​​to 0 , but that will take forever. Anyway, can I set all the values ​​to 0 at the same time?

Loop 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 

Conclusion:

 {'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} 
+6
source share
4 answers

You want dict.fromkeys() :

 a = dict.fromkeys(a, 0) 
+21
source

Thanks @akaRem for the comment :)

 a = dict.fromkeys( a.iterkeys(), 0 ) 
+5
source

Be careful if the order of your keys depends on the solution, it may not be suitable, as it seems to be reordering.

To stop this, use a list comprehension:

 aDictionary = { x:0 for x in aDictionary} 

Note: Only 2.7.x and 2.x exclusive

+1
source

If you know what your dict values ​​should be, you can do this:

  • save dict values ​​in array.array object. It uses a continuous block of memory.
  • dict, and not storing the actual values, will store the index of the array in which the actual value can be found.
  • reinitialize a continuous binary string of zeros

I did not test the performance, but it should be faster ...

 import array class FastResetDict(object): def __init__(self, value_type): self._key_to_index = {} self._value_type = value_type self._values = array.array(value_type) def __getitem__(self, key): return self._values[self._key_to_index[key]] def __setitem__(self, key, value): self._values.append(value) self._key_to_index[key] = len(self._values) - 1 def reset_content_to_zero(self): zero_string = '\x00' * self._values.itemsize * len(self._values) self._values = array.array(self._value_type, zero_string) fast_reset_dict = FastResetDict('i') fast_reset_dict['a'] = 103 fast_reset_dict['b'] = -99 print fast_reset_dict['a'], fast_reset_dict['b'] fast_reset_dict.reset_content_to_zero() print fast_reset_dict['a'], fast_reset_dict['b'] 
0
source

All Articles