On 1/12/2016 11:50 AM, 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

The intended use of dict views: "Dictionary views can be iterated over to yield their respective data, and support membership tests:"

"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?

Using the values views at intended (as an iterable):

>>> dv = d.values()
>>> next(iter(dv))
1

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to