相关疑难解决方法(0)

Pythonic方式从字典中访问任意元素

我有一本字典,里面装满了物品.我想偷看一个单一的,任意的项目:

print "Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)
Run Code Online (Sandbox Code Playgroud)

我不在乎哪个项目.它不需要是随机的.

我可以想到许多实现这一点的方法,但它们看起来都很浪费.我想知道在Python中是否有任何首选习语,或者(如果我错过了一个)(甚至更好).

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
Run Code Online (Sandbox Code Playgroud)

我处于这样一个位置:性能不够严重,这很重要(还),所以我可以被指责过早优化,但我正在努力改进我的Python编码风格,所以如果有一个易于理解的变体,采用它会很好.

python

24
推荐指数
2
解决办法
6394
查看次数

标签 统计

python ×1