我想解析一个字典,它有一个从外部程序传入的变量键名
d = {"Something": {"one": 1, "two": 2, "three": 3}}
或
d = {"ADifferentName": {"one": 11, "two": 22, "three": 33}}
我希望以比以下更好的方式引用Something
或ADifferentName
下的值:
value = d[list(d.keys())[0]]
我做了一些研究,没有发现比iter()
和两行代码更好的东西。难道没有内置Python说“只要给我第一个键,我不管它叫什么”吗
如果您知道字典将只包含一个键值对,则可以使用赋值(注意target list中的逗号)来提取键或值:
如果键的数量不是一,则会抛出
ValueError
:与您的代码完全相同,但没有键(它仅适用于长度为1的字典):
至于钥匙:
正如comments中的L3viathan所建议的,您可以使用
iter
和next
访问第一个键或值:这比构建一个列表然后索引到其中更有效,尽管这对于小型词典来说可能并不重要
相关问题 更多 >
编程相关推荐