Sets in Python

thebjorn BjornSteinarFjeldPettersen at gmail.com
Thu Sep 20 09:50:20 CEST 2007


On Sep 20, 6:02 am, Karthik Gurusamy <kar1... at gmail.com> wrote:
> On Sep 19, 7:17 pm, Steven D'Aprano <st... at REMOVE-THIS-
>
[...]
> > (2) Allow the hash of mutable objects to change, which means you can use
> > mutable objects as keys in dicts but if you change them, you can no
> > longer find them in the dict. They'll still be there, using up memory,
> > but you can't get to them.
>
> In the new model, at the time of addition, you need to remember the
> key at that time. If it's a list, you make a copy of the items.

Eek! Barf! Gag me with a spoon! etc. etc. :-)

And you mean a deep-copy, not just a copy, right?

Or perhaps you were thinking of something like this (mdict ::= mutable
dict):

class mdict(dict):
    def __setitem__(self, k, val):
        super(mdict,self).__setitem__(`k`, val)
    def __getitem__(self, k):
        return super(mdict,self).__getitem__(`k`)
    def __contains__(self, k):
        return super(mdict,self).__contains__(`k`)
    def keys(self):
        return list(eval(k) for k in super(mdict,self).keys())
    def __iter__(self):
        for k in super(mdict,self).__iter__():
            yield eval(k)
    def items(self):
        return list((eval(k),v) for k,v in super(mdict,self).items())
    def __repr__(self):
        items = ', '.join('%s: %s' % (k,repr(v)) for k,v in
self.items())
        return '{' + items + '}'

I think it does what you want..?:

>>> m = mdict()
>>> a, b = [], [1,2]
>>> print m
{}
>>> m[a] = a
>>> m[b] = b
>>> m
{[1, 2]: [1, 2], []: []}
>>> m.keys()
[[1, 2], []]
>>> for k in m:
...     m[k].append('foo')
...
>>> m
{[1, 2]: [1, 2, 'foo'], []: ['foo']}
>>> m.items()
[([1, 2], [1, 2, 'foo']), ([], ['foo'])]
>>> m.values()
[[1, 2, 'foo'], ['foo']]
>>> a in m
False
>>> a
['foo']
>>> b
[1, 2, 'foo']
>>> [] in m
True
>>> [1,2] in m
True
>>> m[{'key':['val']}] = 'this works too'

It'll work for all keys, k, where eval(`k`) == k, and repr(a) ==
repr(b) when a == b (I'm pretty sure the latter isn't always true for
dicts, although I haven't looked at the implementation.)

-- bjorn




More information about the Python-list mailing list