Can you set a dictionary value dependant on anothe

2019-02-15 14:42发布

问题:

Here's the thought:

dict1 = {key1:3, key2:5, key3:key1+key2}
# so key3 relate to the value: 8 (3+5)
dict1.update({key2:6})
# key3 will now relate to the value: 9 (3+6)

I'm trying to avoid updating more entries than necessary as well as building new relations of key-value that's based on values that has already been calculated in a series of lookups and updates while comparing values of relations. The dictionarys' hashability is crucial to get me a more or less constant time on lookup.

回答1:

This isn't a general solution but roughly works for your example:

class DynamicDict(dict):
    def __getitem__(self, key):
        value = super(DynamicDict, self).__getitem__(key)
        return eval(value, self) if isinstance(value, str) else value

>>> d = DynamicDict(key1=3, key2=5, key3='key1+key2')
>>> d.update({'key2': 6})
>>> d['key3']
9


回答2:

You can do this by creating a subclass of dict and overriding the __getitem__ method:

class My_dict(dict):
    def __getitem__(self, key):
        if key == 'key3':
            return self['key1'] + self['key2']
        return dict.__getitem__(self, key)

dict1 = My_dict(key1=3, key2=5)
print dict1['key3']               #prints 8
dict1.update({'key2':6})         
print dict1['key3']               #prints 9