How to get single value from dict with single entry?
我看到了如何提取变量中的字典单键值对,建议:
1 2 | d = {"a":1} (k, v), = d.items() |
但是:我只关心价值。我想把这个值传递给一个方法;比如:
1 | foo(v) |
所以问题是:是否有一个简单的命令既适用于python2,也适用于python3,它直接给出这个值,而不需要绕道"tuple"赋值?
或者,是否有一种方法可以使tuple赋值对调用方法的用例有效?
这两种解决方案都使用python 3.6.0在本地进行测试,而在tio中使用python 2进行测试。
它还可以执行最佳的可用选项(在python 3.6上测试):
1 2 3 4 5 | d = [{'a': i} for i in range(100000)] %timeit [next(iter(i.values())) for i in d] # 50.1 ms per loop %timeit [list(i.values())[0] for i in d] # 54.8 ms per loop %timeit [list(i.values()).pop() for i in d] # 81.8 ms per loop |
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?
使用
1 2 | d = {"a":1} foo(d.copy().popitem()[1]) |
如果你知道钥匙,你可以简单地做:
1 2 3 | d["a"] output : 1 |
如果你不知道钥匙:
1 2 3 4 5 6 7 | for key in d.keys(): d[key] #so basically you have to do : for key in d.keys(): f00(d[key]) |