[ create a new paste ] login | about

Link: http://codepad.org/ujVqYUWG    [ raw code | output | fork ]

Python, pasted on Nov 12:
class IndexedDict(object):
    def __init__(self, *args, **kwargs):
        d = dict(*args, **kwargs)
        self._keys = d.keys()
        self._d = d

    def __getitem__(self, item):
        if isinstance(item, int):
            key = self._keys[item]
            return self._d[key]
        elif isinstance(item, slice):
            keys = self._keys[item]
            return tuple(self._d[key] for key in keys)
        else:
            return self._d[key]

    def __setitem__(self, item, value):
        if isinstance(item, int):
            key = self._keys[item]
            self._d[key] = value
        elif isinstance(item, slice):
            # we only handle slices that don't require the creation of
            # new keys.
            keys = self._keys[item]
            if not len(keys) == len(value):
                raise ValueError("Complain here")
            for key, v in zip(keys, value):
                self._d[key] = v
        else:
            self._d[item] = value
            if item not in self._keys:
                # This is the only form that can create a new element
                self._keys.append(item)


    def __delitem__(self, item):
        if isinstance(item, int):
            key = self._keys[item]
            del self._keys[item]
            del self._d[key]
        elif isinstance(item, slice):
            keys = self._keys[item]
            del self._keys[item]
            for key in keys:
                del self._d[key]
        else:
            del self._d[item]
            self._keys.remove(item)

    def __contains__(self, item):
        if isinstance(item, int):
            return i < len(self._keys)
        else:
            return i in self._d

    # Just for debugging. Not intended as part of API.
    def assertions(self):
        assert len(self._d) == len(self._keys)
        assert set(self._d.keys()) == set(self._keys)


if __name__ == '__main__':
    d = IndexedDict(a=1, b=2, c=3)
    print d[:]
    d.assertions()

    d[1] = 4
    print d[:]
    d.assertions()

    d[::2] = [4, 4]
    print d[:]
    d.assertions()


    d['a'] = 5
    print d[:]
    d.assertions()

    del d['a']
    print d[:]
    d.assertions()

    del d[-1]
    print d[:]
    d.assertions()

    d['d'] = 3
    print d[:]
    d.assertions()

    del d[:1]
    print d[:]
    d.assertions()


Output:
1
2
3
4
5
6
7
8
(1, 3, 2)
(1, 4, 2)
(4, 4, 4)
(5, 4, 4)
(4, 4)
(4,)
(4, 3)
(3,)


Create a new paste based on this one


Comments: