Search code examples
pythonpython-3.xdictionaryiterable-unpacking

How to unpack dict with one key-value pair to two variables more elegantly?


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.


Solution

  • 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.