Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - How to get single value from dict with single entry?

I saw How to extract dictionary single key-value pair in variables suggesting:

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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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())) is another possibility (probably more memory efficient, as you do not need to create a list)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...