retrieve key of only element in a dictionary (Python 3)
Martin A. Brown
martin at linux-ip.net
Fri Mar 18 22:21:06 EDT 2016
>> 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.
>
>When you iterate over a dictionary, you get its keys:
>
>scores = {"Fred": 10, "Joe": 5, "Sam": 8}
>for person in scores:
> print(person)
>
>So unpacking will give you those keys - in an arbitrary order. Of
>course, you don't care about the order when there's only one.
Oh, right! Clearly, it was nonintuitive (to me), even though I've
written 'for k in d:' many times.
A sequence on the left hand side of an assignment, will tell the
right hand side to iterate.
This also explains something I never quite bothered to understand
completely, because it was so obviously wrong:
>>> a, b = 72
TypeError: 'int' object is not iterable
The sequence on the left hand side signals that it expects the
result of iter(right hand side). But, iter(72) makes no sense, so
Python says TypeError. I'd imagine my Python interpreter is
thinking "Dude, why are you telling me to iterate over something
that is so utterly not iterable. Why do I put up with these
humans?"
I love being able to iterate like this:
for k in d:
do_something_with(k)
But, somehow, this surprised me:
[k] = d
Now that I get it, I would probably use something like the below.
I find the addition of a few characters makes this assignment much
clearer to me.
# -- if len(d) > 1, ValueError will be raised
#
(key,) = d.keys()
And thank you for the reply Chris,
-Martin
--
Martin A. Brown
http://linux-ip.net/
More information about the Python-list
mailing list