errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
如果“error1”不存在,它将失败。我真的必须扩展 dict 吗?
请您参考如下方法:
使用 collections.defaultdict而不是普通的 dict —— 毕竟,这种便利正是引入 default-dict 类型的目的:
>>> import collections
>>> errors = collections.defaultdict(tuple)
>>> errors['id'] += ('error1',)
>>> errors['id'] += ('error2',)
>>> errors['id']
('error1', 'error2')
