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