How to extract dictionary single key-value pair in

2019-02-11 16:05发布

I have only a single key-value pair in 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 single statement?

7条回答
相关推荐>>
2楼-- · 2019-02-11 16:16

This is best if you have many items in the dictionary, since it doesn't actually create a list but yields just one key-value pair.

k, v = next(d.iteritems())

Of course, if you have more than one item in the dictionary, there's no way to know which one you'll get out.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-11 16:19
>>> d = {"a":1}
>>> [(k, v)] = d.items()
>>> k
'a'
>>> v
1

Or using next, iter:

>>> k, v = next(iter(d.items()))
>>> k
'a'
>>> v
1
>>>
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-11 16:22

items() returns a list of tuples so:

(k,v) = d.items()[0]
查看更多
放荡不羁爱自由
5楼-- · 2019-02-11 16:24
    d ={"a":1}

you can do

    k, v = d.keys()[0], d.values()[0]

d.keys() will actually return list of all keys and d.values return list of all values, since you have a single key:value pair in d you will be accessing the first element in list of keys and values

查看更多
SAY GOODBYE
6楼-- · 2019-02-11 16:31

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')
查看更多
The star\"
7楼-- · 2019-02-11 16:36

You have a list. You must index the list in order to access the elements.

(k,v) = d.items()[0]
查看更多
登录 后发表回答