subscripting Python 3 dicts/getting the only value in a Python 3 dict

Peter Otten __peter__ at web.de
Tue Jan 12 13:59:14 EST 2016


Bernardo Sulzbach wrote:

> On Tue, Jan 12, 2016 at 3:32 PM, Peter Otten <__peter__ at web.de> wrote:
>>
>> If there is exactly one item you can unpack:
>>
>>>>> d = {"Wilf's Cafe": 1}
>>>>> k, = d.values()
>>>>> k
>> 1
>>
> 
> I personally don't like that trailing comma, it just looks wrong
> there. But this is very neat.
> 

[k] = d.values()

works the same. I used the tuple here to keep it consistent with all other 
cases where the brackets are superfluous, like

[foo, *bar] = ... 
foo, *bar = ...

etc.




More information about the Python-list mailing list