<p>我有一本字典,里面有很多东西。我想看看一个任意的项目:</p>
<pre><code>print "Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)
</code></pre>
<p>我不在乎哪一项。它不需要是<em>随机</em>。</p>
<p>我可以想出很多方法来实现这一点,但它们似乎都是浪费。我想知道在Python中是否有首选的习惯用法,或者(甚至更好)是否缺少一个。</p>
<pre><code>def arb(dictionary):
# Creates an entire list in memory. Could take a while.
return list(dictionary.values())[0]
def arb(dictionary):
# Creates an entire interator. An improvement.
for item in dictionary.itervalues():
return item
def arb(dictionary):
# No iterator, but writes to the dictionary! Twice!
key, value = dictionary.popitem()
dictionary[key] = value
return value
</code></pre>
<p>我所处的位置的性能还不够关键,所以我可能会被指责为过早优化,但我正在努力改进我的Python编码风格,因此如果有一个易于理解的变体,最好采用它。</p>