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

Fillmore fillmore_remove at hotmail.com
Fri Mar 18 18:08:23 EDT 2016


OK, this seems to do the trick, but boy is it a lot of code. Anythong more pythonic?

 >>> l = list(d.items())
 >>> l
[('squib', '007')]
 >>> l[0]
('squib', '007')
 >>> l[0][0]
'squib'
 >>>


On 03/18/2016 05:33 PM, Fillmore 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




More information about the Python-list mailing list