Update/Append to dictionary
<p>Let's say I have a dictionary like so:</p>

<pre><code>x = {'age': 23,
     'channel': ['a'],
     'name': 'Test',
     'source': {'data': [1, 2]}}
</code></pre>

<p>and a similar one like:</p>

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

<p>if I used this <code>x.update(y)</code> I would lose <code>'channel'</code> 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?</p>

<p>End result should be:</p>

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

<p>I came close with this:</p>

<pre><code>for a,b in y.iteritems():
    try:
        x[a] = x[a] + y[a]
    except:
        x[a] = y[a]
</code></pre>

<p>but it failed when it found a dictionary inside of the dictionary.</p>

<p>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 <em>sets</em> to <em>dicts</em> right ? or the likes of these cases)</p>

<pre><code>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])})
            else:
                x.update({key: list(set(x[key] + y[key]))})
    return x


print deep_update(x, y)
</code></pre>

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

python dictionary