No subject

Chris Angelico rosuav at gmail.com
Wed Mar 23 04:43:39 EDT 2016


On Wed, Mar 23, 2016 at 2:17 PM, Nick Eubank <nickeubank at gmail.com> wrote:
> But Apparently True and 1 hash to the same item and False and 0 hash to the
> same item, so they can easily overwrite (which I spent a while banging my
> head over today).
>
> In other words:
>
>  In[1]:
>      d = {True: 'a', False: 'b'}
>      d[0] = 'z'
>      d[False]
>
> Out[1]:
>      'z'
>
> I understand that True and False are sub-types of ints, but it's not clear
> to me why (i.e. certainly didn't feel intuitive) that they would be treated
> the same as keys.
>
> Relatedly, if this is a desired behavior, any advice one how best to work
> with dictionaries when one wants "True" and 1 to be different? I'm working
> on a function that accepts arguments that may be "True" or 1 (meaning very
> different things) and am seeking a pythonic solution...

(Presumably everywhere that you write "True" you mean the boolean
value True, not the string "True", which would be completely
separate.)

Dictionary keys are defined on the basis of equality, so anything that
compares equal will match:

>>> d = {True: 'a', False: 'b'}
>>> d[0]
'b'
>>> d[0.0]
'b'

Since you have True and 1 meaning very different things, your program
is already somewhat non-Pythonic. So your best solution is probably
going to be something messy, like having your dictionary keys
incorporate the type of the object. This isn't going to be easy or
clean, but if that's what you have to work with, so be it. (It's not
half as bad as the mess I was helping one of my students with; she's
coping with a Python module that's a hyper-thin layer over an HTTP/XML
request, and it simply takes the returned XML blob and naively
converts it into a Python dictionary. Makes for some ugly code - but
that's not her fault.)

ChrisA



More information about the Python-list mailing list