Python字典更新和追加

时间:2013-08-20 12:51:15

标签: python dictionary

我的字典看起来像这样:

{"TIM" : [[xx,yy],[aa,bb]] , "SAM" : [[yy,cc]] }

如果设置中尚未显示值[tt,uu],我想将其添加到"SAM"

此外,我想在[ii,pp]添加“KIM”。

我有两个if:s的解决方案,但有更好的解决方案吗?我该怎么办?

编辑:

    array ={}
    if not name in array :
        array = array, {name : {()}}
    if not (value1,value2,rate) in array[name] :
        array.update({(value1,value2,rate)})

2 个答案:

答案 0 :(得分:2)

使用defaultdict

>>> 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')])})

答案 1 :(得分:2)

您可以使用setdefault方法:

>>> d = {'TIM':[['xx', 'yy'], ['aa', 'bb']], 'SAM':[['yy', 'cc']]}
>>> d.setdefault('SAM', []).append(['tt','uu'])
>>> d.setdefault('KIM', []).append(['ii','pp'])
>>> d
{'TIM': [['xx', 'yy'], ['aa', 'bb']], 'KIM': [['ii', 'pp']], 'SAM': [['yy', 'cc'], ['tt', 'uu']]}
相关问题