53

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?

Georgy
  • 9,972
  • 7
  • 57
  • 66

10 Answers10

91

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')
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
  • 4
    @MartijnPieters, what's the technical explanation behind : `(k, v), = d.items()`. I cannot get my head around the last comma. – dmeu Jul 13 '15 at 06:25
  • @dmeu: it is a tuple assignment, the comma [makes the left-hand side target a tuple](http://stackoverflow.com/questions/3750632/why-does-adding-a-trailing-comma-after-a-variable-name-make-it-a-tuple). – Martijn Pieters Jul 13 '15 at 07:41
  • 1
    @MartijnPieters And what is on the right-hand side? :) I mean why does it no twork without the comma? – dmeu Jul 13 '15 at 08:26
  • 4
    @dmeu: why not *try it out*? `dict.items()` returns an iterable *containing* `(key, value)` pairs. What do you think happens with `foo = dict.items()` vs. `foo, = dict.items()`? The first binds `foo` to whatever `dict.items()` returns (a list in Python 2, a dictionary view in Python 3). `foo, = dict.items()` binds `foo` to the *first element* in the `dict.items()` sequence and throws an exception if there are 0 or more than 1 elements in that sequence. – Martijn Pieters Jul 13 '15 at 08:33
  • 3
    @dmeu: `(k, v), = d.items()` just takes that one step further. Take the first item, a `(key, value)` pair, and assign that to `(k, v)`. – Martijn Pieters Jul 13 '15 at 08:34
  • Whats up with the second comma in the "(k, v), = d.items()" ? – quantum231 Jun 17 '21 at 10:06
  • @quantum231: why not try and see what happens if you removed it? As my answer states, you could replace it with `[(k, v)] = d.items()`, that does exactly the same thing: unpack `d.items()` into a single key and value pair. This is called *tuple unpacking*, or *iterable unpacking*. – Martijn Pieters Jun 17 '21 at 20:30
6

items() returns a list of tuples so:

(k,v) = d.items()[0]
Farhadix
  • 1,263
  • 2
  • 11
  • 25
5
>>> 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
>>>
falsetru
  • 336,967
  • 57
  • 673
  • 597
3
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

Georgy
  • 9,972
  • 7
  • 57
  • 66
its me
  • 127
  • 2
  • 8
  • 1
    you cannot subscribe to dict_keys anymore... you'll get: TypeError: 'dict_keys' object is not subscriptable – ALoR Oct 21 '21 at 07:43
2

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.

kindall
  • 168,929
  • 32
  • 262
  • 294
2

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)]
Georgy
  • 9,972
  • 7
  • 57
  • 66
Eduard
  • 7,080
  • 5
  • 35
  • 61
2

Use the .popitem() method.

k, v = d.popitem()
Pyprohly
  • 563
  • 1
  • 7
  • 7
  • 4
    It's worth noting that `popitem` will also remove the key-value pair from the dictionary. – Georgy Sep 01 '20 at 16:17
1

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

(k,v) = d.items()[0]
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
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)
KevinG
  • 794
  • 2
  • 16
  • 30
0
key = list(foo.keys())[0]
value = foo[key]
help-ukraine-now
  • 3,728
  • 3
  • 15
  • 33