Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #105525 > unrolled thread

Re:

Started byChris Angelico <rosuav@gmail.com>
First post2016-03-23 19:43 +1100
Last post2016-03-23 19:43 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Chris Angelico <rosuav@gmail.com> - 2016-03-23 19:43 +1100

#105525 — Re:

FromChris Angelico <rosuav@gmail.com>
Date2016-03-23 19:43 +1100
SubjectRe:
Message-ID<mailman.38.1458722622.2244.python-list@python.org>
On Wed, Mar 23, 2016 at 2:17 PM, Nick Eubank <nickeubank@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web