繁体   English   中英

同时将字典的所有值替换为零 python

[英]Simultaneously replacing all values of a dictionary to zero python

我有一个非常大的字典,可能有大约10,000 keys/values ,我想同时将所有值更改为0 我知道我可以循环并将所有值设置为0 ,但这需要永远。 无论如何,我可以同时所有值设置为0吗?

循环方法,很慢:

# 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}

你想要dict.fromkeys()

a = dict.fromkeys(a, 0)

感谢@akaRem 的评论:)

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

请注意,如果您的密钥顺序很重要,该解决方案可能不适合,因为它似乎重新排序。

要阻止这种情况发生,请使用列表理解:

aDictionary =  { x:0 for x in aDictionary}

注意:只有 2.7.x 和 2.x 独占

如果您知道您的 dict 值需要是什么类型,您可以这样做:

  1. 将 dict 值存储在 array.array 对象中。 这使用了一个连续的内存块。
  2. dict,而不是存储实际值将存储可以找到实际值的数组索引
  3. 使用连续的二进制零字符串重新初始化数组

没有测试性能,但它应该更快......


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']

要扩展@Daniel Roseman,答案a=a.fromkeys(d,0)的功能相同且速度更快。 此外,如果您打算经常这样做save=dict.fromkeys(a,0)然后调用a=save.copy()这在某些情况下更快(大字典)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM