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

Peter Otten __peter__ at web.de
Tue Jan 12 12:32:50 EST 2016


Nick Mellor wrote:

> Hi all,
> 
> Seemingly simple problem:
> 
> There is a case in my code where I know a dictionary has only one item in
> it. I want to get the value of that item, whatever the key is.
> 
> In Python2 I'd write:
> 
>>>> d = {"Wilf's Cafe": 1}
>>>> d.values()[0]
> 1
> 
> and that'd be an end to it.
> 
> In Python 3:
> 
>>>> d = {"Wilf's Cafe": 1}
>>>> d.values()[0]
> Traceback (most recent call last):
>   File "<input>", line 1, in <module>
> TypeError: 'dict_values' object does not support indexing
> "Wilf's Cafe"
>>>> d[list(d)[0]]
> 1
> 
>>>> for k in d:
> ...     value = d[k]
> ...     break
> ...
>>>> value
> 1
> 
>>>> list(d.values())[0]
> 1
> 
> None of this feels like the "one, and preferably only one, obvious way to
> do it" we all strive for. Any other ideas?

If there is exactly one item you can unpack:

>>> d = {"Wilf's Cafe": 1}
>>> k, = d.values()
>>> k
1





More information about the Python-list mailing list