python - Adding attributes from another dictionary for same key without overwriting -


let's have 2 dictionaries:

d1 = {'a': 2, 'b': 4, 'c': 5, 'd': 6} d2 = {'a': 5, 'c': 4, 'e': 8} 

iterating on second:

for k, v in d2.items(): 

i check key presence in d1, , if it's there add value attribute key , if not, add dictionary want:

d1 = {'a': [2, 5], 'b': 4, 'c': [4, 5], 'd': 6, 'e': 8} 

i know how check presence in operator can't work out how update dict new attributes. bear in mind, have presented simple case of problem , within loop means key have multiple attributes rather 1 or 2.

thank you.

you can't have 2 values 1 key in dictionary. that, need value list append "real" values key.

for k,v in d2.items():     if k in d1:         if isinstance(d1[k], list):             d1[k].append(v)         else:             d1[k] = [d1[k], v]      else:         d1[k] = v 

however, seems more straightforward:

for k,v in d2.items():     if k in d1:         d1[k].append(v)      else:         d1[k] = [v] 

update

sum of dictionary values, assuming thing need total sum:

replace above code with:

for k,v in d2.items():     if k in d1:         d1[k] = [sum(d1[k] + [v])]      else:         d1[k] = [v] 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -