使用默认字典
>>> from collections import defaultdict
>>> d = defaultdict(list) # create the dictionary, then populate it.
>>> d.update({"TIM":[['xx', 'yy'], ['aa', 'bb']], "SAM":[['yy', 'cc']]})
>>> d # see its what you wanted.
defaultdict(<type 'list'>, {'TIM': [['xx', 'yy'], ['aa', 'bb']], 'SAM': [['yy', 'cc']]})
>>> d["SAM"].append(['tt','uu']) # add more items to SAM
>>> d["KIM"].append(['ii','pp']) # create and add to KIM
>>> d # see its what you wanted.
defaultdict(<type 'list'>, {'TIM': [['xx', 'yy'], ['aa', 'bb']], 'KIM': [['ii', 'pp']], 'SAM': [['yy', 'cc'], ['tt', 'uu']]})
如果您希望设置字典值,那没问题:
>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> d.update({"TIM":set([('xx', 'yy'), ('aa', 'bb')]), "SAM":set([('yy', 'cc')])})
>>> d["SAM"].add(('tt','uu'))
>>> d["KIM"].add(('ii','pp'))
>>> d
defaultdict(<type 'set'>, {'TIM': set([('xx', 'yy'), ('aa', 'bb')]), 'KIM': set([('ii', 'pp')]), 'SAM': set([('tt', 'uu'), ('yy', 'cc')])})