« Back to Index

Python subclass dictionary

View original Gist on GitHub

python subclass dictionary.py

class MyDict(OrderedDict):
    def __init__(self):
        super().__init__()

    def __setitem__(self, key, value):
        # set device_type to mobile by default, and allow override to be provided
        value = {'device_type': 'mobile', **value} if not value.get('device_type') else {**value}
        print('value set is {}'.format(value))
        super().__setitem__(key, value)

d = MyDict()
dict(d)  # {}

d['foo'] = {'beep': 'boop'}
# value set is {'device_type': 'mobile', 'beep': 'boop'}

d['bar'] = {'device_type': 'something', 'beep': 'boop'}
# value set is {'device_type': 'something', 'beep': 'boop'}

dict(d)  
# {'bar': {'beep': 'boop', 'device_type': 'something'}, 'foo': {'beep': 'boop', 'device_type': 'mobile'}}