6

Currently, I'm using this:

d = {'a': 'xyz'}
k, v = list(*d.items())

The starred expression is required here, as omitting it causes the list function/constructor to return a list with a single tuple, which contains the key and value.

However, I was wondering if there were a better way to do it.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
m01010011
  • 895
  • 8
  • 13

3 Answers3

9

Keep nesting:

>>> d = {'a': 'xyz'}
>>> ((k,v),) = d.items()
>>> k
'a'
>>> v
'xyz'

Or equivalently:

>>> (k,v), = d.items()
>>> k
'a'
>>> v
'xyz'
>>>

Not sure which I prefer, the last one might be a bit difficult to read if I was glancing at it.

Note, the advantage here is that it is non-destructive and fails if the dict has more than one key-value pair.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
5

Since dict items do not support indexed access, you might resort to the following non-mutating retrieval of the first (and only) item:

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

This has the advantage of not only working for dicts of any size, but remaining an O(1) operation which other solutions that unpack the items or convert them to a list would not.

user2390182
  • 72,016
  • 6
  • 67
  • 89
4

If you don't mind the dictionary getting altered, this'll do:

k, v = d.popitem()
deceze
  • 510,633
  • 85
  • 743
  • 889