subscripting Python 3 dicts/getting the only value in a Python 3 dict
Steven D'Aprano
steve at pearwood.info
Tue Jan 12 20:23:52 EST 2016
On Wed, 13 Jan 2016 03: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.
[snip examples]
> None of this feels like the "one, and preferably only one, obvious way to
> do it" we all strive for. Any other ideas?
That's because this is a somewhat weird case. A dict with only one item that
you don't know the key of? Who does that? (Well, apart from you,
obviously.)
Three solutions:
item = d.popitem()[1] # But this modifies the dict.
# Use tuple rather than list for efficiency.
item = tuple(d.values())[0]
Probably the best solution, because it will conveniently raise an exception
if your assumption that the dict has exactly one item is wrong:
item, = d.values() # Note the comma after "item".
The comma turns the assignment into sequence unpacking. Normally we would
write something like this:
a, b, c, d = four_items
but you can unpack a sequence of one item too. If you really want to make it
obvious that the comma isn't a typo:
(item,) = d.values()
--
Steven
More information about the Python-list
mailing list