False and 0 in the same dictionary

Carl Banks pavlovevidence at gmail.com
Wed Nov 5 08:20:15 EST 2008


On Nov 4, 3:48 pm, Prateek <sure... at gmail.com> wrote:
> I've been using Python for a while (4 years) so I feel like a moron
> writing this post because I think I should know the answer to this
> question:
>
> How do I make a dictionary which has distinct key-value pairs for 0,
> False, 1 and True.
> As I have learnt, 0 and False both hash to the same value (same for 1
> and True).
>
> >>> b = {0:'xyz', False:'abc'}
> >>> b
>
> {0: 'abc'}  # Am I the only one who thinks this is weird?
>
> This obviously stems from the fact that 0 == False but 0 is not False
> etc. etc.
>
> That doesn't help my case where I need to distinguish between the two
>
> The same issue applies in a list:
>
> Suppose I do:
>
> >>> a = [0, 1, True, False]
> >>> a.index(False)
>
> 0
>
> Wha??? Help.


Let me suggest using surrogate objects instead of True and False:

class TrueObject(object):
    def __nonzero__(self):
        return True

class FalseObject(object):
    def __nonzero__(self):
        return False

DistinctTrue = TrueObject()
DistinctFalse = FalseObject()


If that doesn't work and you really need the actual True and False
objects to be distinct, it's not too hard to special case a dict to
get it:

class special_dict(dict):
    def __init__(self,*args,**kwargs):
        self.true_surrogate = object()
        self.false_surrogate = object()
        super(special_dict,self).__init__(*args,**kwargs)
    def __getitem__(self,value):
        if value is True:
            value = self.true_surrogate
        elif value is False:
            value = self.false_surrogate
        super(special_dict,self).__getitem__(value)
    ## etc.


Carl Banks



More information about the Python-list mailing list