Overriding dict constructor

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Sep 20 13:11:51 CEST 2010

I have a dict subclass that associates extra data with each value of the 
key/value items:

class MyDict(dict):
    def __setitem__(self, key, value):
        super(MyDict, self).__setitem__(key, (value, "extra_data"))
    def __getitem__(self, key):
        return super(MyDict, self).__getitem__(key)[0]
    # plus extra methods

This works fine for item access, updates, etc:

>>> d = MyDict()
>>> d[0] = 'a'; d[1] = 'b'
>>> d[1]

But if I try to create a regular dict from this, dict() doesn't call my 
__getitem__ method:

>>> dict(d)
{0: ('a', 'extra_data'), 1: ('b', 'extra_data')}

instead of {0: 'a', 1: 'b'} as I expected.

How can I fix this?


More information about the Python-list mailing list