如何通过一次输入从dict中获得单个值? [英] How to get single value from dict with single entry?

查看:127
本文介绍了如何通过一次输入从dict中获得单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了如何提取字典单键-变量中的值对建议:

d = {"a":1}
(k, v), = d.items()

但是:我只关心.我想将该值传递给方法;像:

But: I only care about the value. And I want to pass that value to a method; like:

foo(v)

所以问题是:是否有一个适用于python2和python3的简单命令,直接为我提供了该值,而没有绕过元组"分配?

So the question is: is there a simple command that works for both python2 and python3 that gives me that value directly, without the detour of the "tuple" assignment?

还是有一种方法可以使元组赋值在我调用方法的用例中起作用?

Or is there a way to make the tuple assignment work for my usecase of calling a method?

推荐答案

list(d.values())[0]将被评估为1. 如评论中所指出的,仅在python3中需要强制转换为list.

list(d.values())[0] will be evaluated to 1. As pointed out in the comments, the cast to list is only needed in python3.

next(iter(d.values()))是另一种可能性(可能会提高内存效率,因为您无需创建列表)

next(iter(d.values())) is another possibility (probably more memory efficient, as you do not need to create a list)

这两个解决方案均使用python 3.6.0在本地进行测试,并且在 a>.

Both solution testes locally with python 3.6.0 and in TIO with python 2.

这篇关于如何通过一次输入从dict中获得单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆