0 equals False, was Re: (unknown)
gst
g.starck at gmail.com
Wed Mar 23 11:03:32 EDT 2016
Le mercredi 23 mars 2016 04:52:02 UTC-4, Peter Otten a écrit :
> Nick Eubank wrote:
>
> > Hello All,
> >
> >
> > Found an odd behavior I'd never known about today, not sure if it's a bug
> > or known. Python 3.4.4 (anaconda).
> > True, False, 0, 1 can all be used as dictionary keys.
> >
> > 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...
I would include the type in the dictionary key:
d = {}
x = True
d[(type(x), x)] = 42
x = 1
d[(type(x), x)] = "foo"
More information about the Python-list
mailing list