retrieve key of only element in a dictionary (Python 3)
Martin A. Brown
martin at linux-ip.net
Fri Mar 18 21:27:43 EDT 2016
OK, so ... I'll bite!
>>> d = {"squib": "007"}
>>> key, = d
Why exactly does this work?
I understand why the following three are similar and why they all
work alike in this situation:
key, = d
(key,) = d
[key] = d
I also, intuitively understand that, if the dictionary d contains
more than 1 key, that the above assignments would cause:
ValueError: too many values to unpack
But, I still don't understand why this works and can't puzzle it
out. I see a sequence on the left of the assignment operator and a
dictionary (mapping) on the right.
I looked through the dunder methods [0], but none of them explained
this, apparently, left-hand-side context-sensitive, behaviour to me.
Could somebody explain?
-Martin
[0] for dict(), I found: __cmp__, __contains__, __delitem__,
__eq__, __ge__, __getattribute__, __getitem__, __gt__,
__init__, __iter__, __le__, __len__, __lt__, __ne__,
__repr__, __setitem__ and __sizeof__
--
Martin A. Brown
http://linux-ip.net/
More information about the Python-list
mailing list