errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
如果'error1'不存在,则会失败。我真的需要扩展dict吗?
答案 0 :(得分:4)
使用collections.defaultdict
而不是普通的dict
- 毕竟,这种方便性正是引入default-dict类型的原因:
>>> import collections
>>> errors = collections.defaultdict(tuple)
>>> errors['id'] += ('error1',)
>>> errors['id'] += ('error2',)
>>> errors['id']
('error1', 'error2')
答案 1 :(得分:3)
import collections
errors = collections.defaultdict(tuple)
答案 2 :(得分:1)
>>> from collections import defaultdict
>>> errors = defaultdict (tuple)
>>> errors['id'] += ('blargh',)
>>> errors['id']
('blargh',)