3

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
  • 77,035
  • 9
  • 115
  • 152
m01010011
  • 725
  • 5
  • 12

3 Answers3

8

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
  • 77,035
  • 9
  • 115
  • 152
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
  • 67,685
  • 6
  • 55
  • 77
3

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

k, v = d.popitem()
deceze
  • 491,798
  • 79
  • 706
  • 853