<p>这个答案是基于OP对我的评论的回答。我问他会用dict做什么,暗示也许他一开始就不需要构建它。@西蒙回答:</p>
<blockquote>
<p>i add it to an excel sheet, so I take the KEY, which is the name, and
put it in A1, then I take the VALUE, which is
1345,345,135,346,3451,35.. etc etc, and put that into A2. then I do
the rest of my programming with that information...... but i need
those values seperated by commas and acessible inside that excel sheet
like that!</p>
</blockquote>
<p>所以看起来dict根本不需要构建。这里有一个替代方法:为每个名称创建一个文件,并将这些<em>文件</em>存储在^{<cd1>中:</p>
<pre><code>files = {}
name = 'John' # let's say
if name not in files:
files[name] = open(name, 'w')
</code></pre>
<p>然后,当您在50k行的excel上循环时,您可以执行如下操作(伪代码):</p>
^{pr2}$
<p>由于您的<code>value_string</code>已经用逗号分隔,所以您的文件将是csv格式的,而不会对您的部分进行任何进一步的调整(除了您可能希望在完成后去掉最后一个逗号)。然后当您需要John的值时,只需<code>value = open('John').read()</code>。在</p>
<p>现在我从未使用过50k row excels,但是如果这不是比您现在的速度快一点,我会非常惊讶的。拥有持久性数据也是一个优点。在</p>
<hr/>
<p>编辑:</p>
<p>以上是一个面向内存的解决方案。写入文件比追加到列表慢得多(但可能比重新创建许多大字符串还要快)。但是如果列表很大(这看起来很可能),并且您遇到内存问题(不是说您会),您可以尝试使用文件方法。在</p>
<p>另一种方法,类似于性能列表(至少对于我尝试过的玩具测试)是使用<code>StringIO</code>:</p>
<pre><code>from io import StringIO # python 2: import StringIO import StringIO
string_ios = {'John': StringIO()} # a dict to store StringIO objects
for value in ['ab', 'cd', 'ef']:
string_ios['John'].write(value + ',')
print(string_ios['John'].getvalue())
</code></pre>
<p>这将输出<code>'ab,cd,ef,'</code></p>