False and 0 in the same dictionary

Arnaud Delobelle arnodel at googlemail.com
Tue Nov 4 16:45:32 EST 2008


Prateek <surekap at gmail.com> writes:

> On Nov 5, 1:52 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
>> 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.
>>
>> 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.
>
> Is there a better way?
> I also thought of using a custom __eq__  method in a custom class
> which extends the dict type but decided that was even worse.
>
> Prateek

You could use currying on Duncan's solution :).  It would
give something like this (minimal implementation):

from collections import defaultdict

class DictByType(object):
      def __init__(self):
            self.dicts = defaultdict(dict)
      def __setitem__(self, key, val):
            self.dicts[type(key)][key] = val
      def __getitem__(self, key):
            return self.dicts[type(key)][key]


Then:

>>> d = DictByType()
>>> d[1]='foo'
>>> d[True]='bar'
>>> d[1.0] = 'foobar'
>>> d[1], d[True], d[1.0]
('foo', 'bar', 'foobar')

If, as seems to be the case, you have many keys with few types, then the
memory overhead will be smaller.  Access time might suffer though.

-- 
Arnaud



More information about the Python-list mailing list