我有一本看起来像这样的字典:
{"TIM" : [[xx,yy],[aa,bb]] , "SAM" : [[yy,cc]] }
Run Code Online (Sandbox Code Playgroud)
我想添加一个值[tt,uu]("SAM"如果集合中尚不存在)。
另外我想添加“KIM” [ii,pp]。
我有一个包含两个if:s 的解决方案,但是有更好的解决方案吗?我怎样才能做这些事情呢?
编辑:
array ={}
if not name in array :
array = array, {name : {()}}
if not (value1,value2,rate) in array[name] :
array.update({(value1,value2,rate)})
Run Code Online (Sandbox Code Playgroud)
使用默认字典
>>> 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']]})
Run Code Online (Sandbox Code Playgroud)
如果您希望设置字典值,那没问题:
>>> 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')])})
Run Code Online (Sandbox Code Playgroud)