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

Joel Goldstick joel.goldstick at gmail.com
Fri Mar 18 18:52:25 EDT 2016


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

>
> 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'


Maybe this:
l = list(d.items())[0][0]

>
> >>>
>
>
> 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
>>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com/ <http://joelgoldstick.com/stats/birthdays>
http://cc-baseballstats.info/



More information about the Python-list mailing list