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

Chris Angelico rosuav at gmail.com
Tue Jan 12 12:06:20 EST 2016


On Wed, Jan 13, 2016 at 3:50 AM, Nick Mellor <thebalancepro at gmail.com> wrote:
> 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

You could try:

next(iter(d.values()))

but honestly, this isn't all that common a situation, so I'm not
surprised there's no really simple and clean way to do it.

ChrisA



More information about the Python-list mailing list