Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary Update and Append

I have a dictionary looking like this:

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

I want to add a value [tt,uu] to "SAM" if not present yet in the set.

Also I want to add "KIM" with [ii,pp].

i have a solution with two if:s, but is there a better one? How can I do these things?

edit:

    array ={}
    if not name in array :
        array = array, {name : {()}}
    if not (value1,value2,rate) in array[name] :
        array.update({(value1,value2,rate)})
like image 822
to4dy Avatar asked Sep 20 '25 06:09

to4dy


1 Answers

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

If you want the dictionary values to be sets, that is no problem:

>>> 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')])})
like image 105
Inbar Rose Avatar answered Sep 21 '25 20:09

Inbar Rose