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

Nick Mellor thebalancepro at gmail.com
Tue Jan 12 11:50:41 EST 2016


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?

Thanks,

Nick



More information about the Python-list mailing list