Merging Dicts that have Lists of Dicts in Python 2.7
<p>I am trying to merge two <code>dict</code>s in Python that could be The same or one could have far less info </p>

<p>ex.</p>

<pre><code>master = {"a": 5564, "c": [{"d2":6}]}
daily = { "a": 795, "b": 1337, "c": [{"d1": 2,"d2": 2,"d3": [{"e1": 4,"e2": 4}]}]}
</code></pre>

<p>They need to be merged so the output is as such</p>

<pre><code>master = { "a": 6359, "b": 1337, "c": [{"d1": 2,"d2": 8,"d3": [{"e1": 4,"e2": 4}]}]}
</code></pre>

<p>I took a shot at it though I only ever get returned null. I might be missing something or just way off. I just cant figure it out. Any help would be amazing Thank you. </p>

<pre><code>def merge(master,daily):
    for k, v in daily.items():
        if isinstance(daily[k],list):
            key_check = keyCheck(k, master)
            if key_check:
                merge(master[k],daily[k])
            else :
                master[k] = daily[k]
        else :
            if keyCheck(k, master):
                 master[k] += daily[k]
            else :
                master[k] = daily[k]
</code></pre>

<p><code>keyCheck</code> only checks if a key is in the dictionary so it doesn't throw errors.</p>

<p>Here is a one linear using <code>collections.Counter()</code>:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt; C2 = Counter(daily)
&gt;&gt;&gt; C1 = Counter(master)
&gt;&gt;&gt; 
&gt;&gt;&gt; {k:reduce(lambda x,y : Counter(x)+Counter(y), v) if isinstance(v, list) and k in (C1.viewkeys() &amp; C2) else v for k, v in (C1 + C2).items()}
{'a': 6359, 'c': Counter({'d3': [{'e1': 4, 'e2': 4}], 'd2': 8, 'd1': 2}), 'b': 1337}
</code></pre>

<p>First off, you can convert your dictionaries to Counter objects in order to add the values for common keys after summing the counters (that's how Counter's add attribute works), then you can loop over the items and for keys that exist in both counters and their values are lists, you can use the <code>reduce()</code> function to apply the same algorithm to all of the list items too. </p>

<p>If your list contains another nested similar data structure, you can convert this code to a recursive function.</p>

python python-2.7 dictionary