retrieve key of only element in a dictionary (Python 3)

Chris Angelico rosuav at gmail.com
Fri Mar 18 21:05:39 EDT 2016


On Sat, Mar 19, 2016 at 10:03 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
>   >>> d = {"squib": "007"}
>   >>> key, = d
>   >>> key
>   'squib'
>
> I'd put a comment on the line to make it clear what's going on since
> that comma is easy to miss, but based on Alex Martelli's testing[2],
> it was the fastest of the proposed solutions.
>

As an alternative, you can spell the same thing with square brackets:

>>> d = {"squib": "007"}
>>> [key] = d
>>> key
'squib'

Might be easier to read than a loose comma.

ChrisA



More information about the Python-list mailing list