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

标签 python

我有一本字典,里面有很多东西。我想偷看一个任意的项目:

print("Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary))

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

我可以想出很多方法来实现这一点,但它们似乎都很浪费。我想知道是否有任何 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 iterator. An improvement.
    for item in dictionary.values():
        return item

def arb(dictionary):
# No iterator, but writes to the dictionary! Twice!
    key, value = dictionary.popitem()
    dictionary[key] = value
    return value

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

最佳答案

在我看来,类似于您的第二个解决方案,但更明显:

return next(iter(dictionary.values()))

这在 python 2 和 python 3 中都有效,但在 python 2 中这样做更有效:

return next(dictionary.itervalues())

关于从字典中访问任意元素的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10593651/

相关文章:

Python正则表达式从C头文件中提取数据

python - 看到我尝试让 Flask 运行有什么问题了吗? (mod_wsgi + 虚拟环境)

python - 函数和采样数据Python的双重积分

python - Django 休息框架没有正确读取 JSON

python - 在 Bokeh 1.4.0 中使用 box_select 工具“隐藏”而不是 'mute' 字形

python - Python 中向后兼容的输入调用

Python:any() 意外性能

python - 在 Caffe 中加载自定义 Python 层导入错误

python - 如何使用 find() 查找整个字符串

python - 使用子进程打开 Windows 快捷方式文件 `.lnk`