-2

I would like to update a python dict without overwrite.

It would be something like :

d1 = {id1 : val1, id2 : val2}
d2 = {id1 : val3, id3 : val4}

d1 + d2 = {id1 : [val1, val3], id2 : [val2], id3 : [val4]}

Do you have any ideas ?

Ranisterio
  • 107
  • 1
  • 6
  • This is answered here: [Combining Dictionaries Of Lists In Python](https://stackoverflow.com/questions/1495510/combining-dictionaries-of-lists-in-python) – mkrieger1 May 18 '20 at 13:37

1 Answers1

0

Sounds like you need a function that creates new lists for each key and then appends to them if necessary.

d1 = {'id1' : 'val1', 'id2' : 'val2'}
d2 = {'id1' : 'val3', 'id3' : 'val4'}

def concatDicts(d1,d2):
    dsum = {}
    for key in d1:
        if key not in dsum:
            dsum[key] = [d1[key]]
    for key in d2:
        if key not in dsum:
            dsum[key] = []
        dsum[key].append(d2[key])
    return dsum

d3 = concatDicts(d1,d2)
print(d3)
# d3 = {id1 : [val1, val3], id2 : [val2], id3 : [val4]}
Ted Brownlow
  • 1,103
  • 9
  • 15