在 Ruby 和 Python 中为散列预分配内存,类似于 Perl 的键 %hash = num

pre allocation of memory in Ruby and Python for hashes, akin to Perl's keys %hash = num

我可能不得不在以后的代码中处理非常大的散列。在 Perl 中,如果事先知道要创建一个巨大的散列,那么可以使用以下代码预分配内存(假设需要 10 亿大小的散列):

keys %hash = 1e9

Ruby 或 Python 中是否有类似的内容?

当使用 Python 时,dict.fromkeys() 可用于创建新字典,其中的键来自 seq,值设置为值(在本例中为空)。

dict.fromkeys(xrange(1000000))