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

Larry Martell larry.martell at gmail.com
Fri Mar 18 17:39:30 EDT 2016


On Fri, Mar 18, 2016 at 5: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

list(d.keys())[0]



More information about the Python-list mailing list