以下是这个想法:
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)
我正在尝试避免更新超过必要条目的更多条目,以及建立新的键值关系,该关系基于已经在一系列查找和更新中计算的值,同时比较关系值。 dictionarys的可靠性对于让我或多或少地保持查找时间至关重要。
答案 0 :(得分:6)
这不是一般解决方案,但大致适用于您的示例:
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
答案 1 :(得分:0)
您可以通过创建dict
的子类并覆盖__getitem__
方法来执行此操作:
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