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
221 views
in Technique[技术] by (71.8m points)

python - How to extract dictionary single key-value pair in variables

I have only a single key-value pair in a dictionary. I want to assign key to one variable and it's value to another variable. I have tried with below ways but I am getting error for same.

>>> d = {"a": 1}

>>> d.items()
[('a', 1)]

>>> (k, v) = d.items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

>>> (k, v) = list(d.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I know that we can extract key and value one by one, or by for loop and iteritems(), but isn't there a simple way such that we can assign both in a single statement?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Add another level, with a tuple (just the comma):

(k, v), = d.items()

or with a list:

[(k, v)] = d.items()

or pick out the first element:

k, v = d.items()[0]

The first two have the added advantage that they throw an exception if your dictionary has more than one key, and both work on Python 3 while the latter would have to be spelled as k, v = next(iter(d.items())) to work.

Demo:

>>> d = {'foo': 'bar'}
>>> (k, v), = d.items()
>>> k, v
('foo', 'bar')
>>> [(k, v)] = d.items()
>>> k, v
('foo', 'bar')
>>> k, v = d.items()[0]
>>> k, v
('foo', 'bar')
>>> k, v = next(iter(d.items()))  # Python 2 & 3 compatible
>>> k, v
('foo', 'bar')

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

...