Can you set a dictionary value dependant on another dictionary entry?

狂风中的少年 提交于 2019-11-30 18:06:34

问题


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


来源:https://stackoverflow.com/questions/22468401/can-you-set-a-dictionary-value-dependant-on-another-dictionary-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!