errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
如果'error1'不存在,将失败。我真的必须扩展字典吗?在空字典中连接元组
errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
如果'error1'不存在,将失败。我真的必须扩展字典吗?在空字典中连接元组
使用collections.defaultdict
,而不是一个简单的dict
- 这种方便,毕竟,正是默认快译通型中引入了:
>>> import collections
>>> errors = collections.defaultdict(tuple)
>>> errors['id'] += ('error1',)
>>> errors['id'] += ('error2',)
>>> errors['id']
('error1', 'error2')
import collections
errors = collections.defaultdict(tuple)
>>> from collections import defaultdict
>>> errors = defaultdict (tuple)
>>> errors['id'] += ('blargh',)
>>> errors['id']
('blargh',)
大THX :) python让我干:) – 2010-06-23 20:27:51