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

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Jan 12 12:47:22 EST 2016


Nick Mellor writes:

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

If you are happy to give the sole value a name:

   >>> shoe = dict(it=math.pi)
   >>> [o] = shoe.values()
   >>> o
   3.141592653589793

You might be able to use * to pass the sole value to a function:

   >>> print(*shoe.values())
   3.141592653589793

But the most readable thing might be to have a function that extracts
the sole value by whatever means:

   >>> def sole(d): [o] = d.values() ; return o
   ... 
   >>> sole(shoe)
   3.141592653589793



More information about the Python-list mailing list