Onilol Onilol - 2 months ago 13
Python Question

Update/Append to dictionary

Let's say I have a dictionary like so:

x = {'age': 23,
'channel': ['a'],
'name': 'Test',
'source': {'data': [1, 2]}}

and a similar one like:

y = {'age': 23,
'channel': ['c'],
'name': 'Test',
'source': {'data': [3, 4], 'no': 'xyz'}}

if I used this
I would lose
previous info for example.. How can I append the values when they are different and add keys/values when they are not already in the dictionary?

End result should be:

{'age': 23,
'channel': ['a', 'c'],
'name': 'Test',
'source': {'data': [1, 2, 3, 4], 'no': 'xyz'}}

I came close with this:

for a,b in y.iteritems():
x[a] = x[a] + y[a]
x[a] = y[a]

but it failed when it found a dictionary inside of the dictionary.


Your requirement seems a bit vague, but you can do what you want with a recursive function like the following. (To the point I understood your requirements, you can't append sets to dicts right ? or the likes of these cases)

x = {'age': 23,
     'channel': ['a'],
     'name': 'Test',
     'source': {'data': [1, 2], 'no': 'jj'}}

y = {'age': 23,
     'channel': ['c'],
     'name': 'Test',
     'source': {'data': [3, 4], 'no': 'xyz'}}

def deep_update(x, y):
    for key in y.keys():
        if key not in x:
            x.update({key: y[key]})
        elif x[key] != y[key]:
            if isinstance(x[key], dict):
                x.update({key: deep_update(x[key], y[key])})
                x.update({key: list(set(x[key] + y[key]))})
    return x

print deep_update(x, y)

{'source': {'data': [1, 2, 3, 4], 'no': 'jjxyz'}, 'age': 23, 'name': 'Test', 'channel': ['a', 'c']}