retrieve key of only element in a dictionary (Python 3)
Tim Chase
python.list at tim.thechases.com
Fri Mar 18 19:03:40 EDT 2016
On 2016-03-18 17:33, Fillmore wrote:
> >>> d = dict()
> >>> d['squib'] = "007"
> >>> key = d.items()[0]
I posted a similar question about 1-element-sets[1] a while back and
Peter Otten & Rene Pijlman both suggested
>>> s = set(["hello"])
>>> element, = s
which, in your case would translate to
>>> 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.
-tkc
[1]
https://mail.python.org/pipermail/python-list/2006-January/392144.html
[2]
https://mail.python.org/pipermail/python-list/2006-January/382654.html
More information about the Python-list
mailing list