How to extract dictionary single key-value pair in variables

大憨熊 提交于 2019-11-30 07:54:27

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')

items() returns a list of tuples so:

(k,v) = d.items()[0]
>>> 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
>>>
    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

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.

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

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

In Python 3:

Short answer:

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

or:

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

or:

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

Long answer:

d.items(), basically (but not actually) gives you a list with a tuple, which has 2 values, that will look like this when printed:

dict_items([('a', 1)])

You can convert it to the actual list by wrapping with list(), which will result in this value:

[('a', 1)]

If you just want the dictionary key and don't care about the value, note that (key, ), = foo.items() doesn't work. You do need to assign that value to a variable.

So you need (key, _), = foo.items()

Illustration in Python 3.7.2:

>>> foo = {'a': 1}
>>> (key, _), = foo.items()
>>> key
'a'
>>> (key, ), = foo.items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)
Kamlakar Ravindra Bhopatkar
key = list(foo.keys())[0]
value = foo[key]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!