从1长度字典中获取值的更好方法?

2024-10-03 06:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析一个字典,它有一个从外部程序传入的变量键名

d = {"Something": {"one": 1, "two": 2, "three": 3}}

d = {"ADifferentName": {"one": 11, "two": 22, "three": 33}}

我希望以比以下更好的方式引用SomethingADifferentName下的值:

value = d[list(d.keys())[0]]

我做了一些研究,没有发现比iter()和两行代码更好的东西。难道没有内置Python说“只要给我第一个键,我不管它叫什么”吗


Tags: 代码程序字典value方式keysone内置
3条回答

如果您知道字典将只包含一个键值对,则可以使用赋值(注意target list中的逗号)来提取键或值:

>>> d = {"Something": {"one": 1, "two": 2, "three": 3}}
>>> key, = d
>>> key
'Something'
>>> value, = d.values()
>>> value
{'one': 1, 'two': 2, 'three': 3}

如果键的数量不是一,则会抛出ValueError

>>> key, = {"foo": 1, "bar": 2}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)

与您的代码完全相同,但没有键(它仅适用于长度为1的字典):

list(d.values())[0]

至于钥匙:

list(d.values())[0].keys()

正如comments中的L3viathan所建议的,您可以使用iternext访问第一个键或值:

>>> d = {"Something": {"one": 1, "two": 2, "three": 3}}
>>> next(iter(d))
'Something'
>>> next(iter(d.values()))
{'one': 1, 'two': 2, 'three': 3}

这比构建一个列表然后索引到其中更有效,尽管这对于小型词典来说可能并不重要

相关问题 更多 >