False and 0 in the same dictionary

John Machin sjmachin at lexicon.net
Thu Nov 6 20:28:07 EST 2008


On Nov 7, 11:54 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Prateek <sure... at gmail.com> writes:
> > > How about using (x, type(x)) as the key instead of just x?
> > Yup. I thought of that. Although it seems kinda unpythonic to do so.
> > Especially since the dictionary is basically a cache mostly containing
> > strings. Adding all the memory overhead for the extra tuples seems
> > like a waste just for those four keys.
>
> You could use a second dict for the other type:
>
>   def lookup(x):
>     if x in dict1: return dict1[x]
>     return dict2[x]
>
> dict1 would have the 4 special keys and dict2 would have the regular
> keys.


Ummm how do you get "the 4 special keys" in dict1?
E.g.
| >>> dict(((0, '0'), (1, '1'), (False, 'f'), (True, 't')))
| {0: 'f', 1: 't'}
| >>> # Whoops!

Unless I'm missing something, the whole reason for the OP's problem is
that 0/False and 1/True are indistinguishable as dict keys (and set
members).

An alternative solution:
def lookup(x):
    if x is False: return FALSE_VALUE
    if x is True: return TRUE_VALUE
    return normal_dict[x]

Cheers,
John



More information about the Python-list mailing list