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

Daniel Wilcox dmw at yubasolutions.com
Fri Mar 18 17:39:50 EDT 2016


I think you're looking for something like popitem().

>>> d = {'asdf':1}
>>> d.popitem()[0]
'asdf'

Cheers


On Fri, Mar 18, 2016 at 2:33 PM, Fillmore <fillmore_remove at hotmail.com>
wrote:

>
> I must be missing something simple, but...
>
> Python 3.4.0 (default, Apr 11 2014, 13:05:11)
> [GCC 4.8.2] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> d = dict()
> >>> d['squib'] = "007"
> >>> # I forget that 'squib' is my key to retrieve the only element in d
> ...
> >>> type(d.items())
> <class 'dict_items'>
> >>> key = d.items()[0]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'dict_items' object does not support indexing
> >>> key,_ = d.items()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: need more than 1 value to unpack
> >>> key,b = d.items()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: need more than 1 value to unpack
> >>> print(d.items())
> dict_items([('squib', '007')])
> >>> print(d.items()[0])
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'dict_items' object does not support indexing
> >>>
>
> what am I missing? I don't want to iterate over the dictionary.
> I know that there's only one element and I need to retrieve the key
>
> thanks
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list