merge two lists of dictionaries in python?
<p>I have two lists of dictionaries:</p>

<pre><code>old = [{'a':'1','b':'2'},{'a':'2','b':'3'},{'a':'3','b':'4'},{'a':'4','b':'5'}]
new = [{'a':'1','b':'100'},{'a':'2','b':'100'},{'a':'5','b':'6'}]
</code></pre>

<p>How can I merge two lists of dictionaries to get:</p>

<pre><code>update = [{'a':'1','b':'2,100'},{'a':'2','b':'3,100'},{'a':'3','b':'4'},{'a':'4','b':'5'},{'a':'5','b':'6'}]
</code></pre>

<p>the idea is if new 'a' is not in the old, add it and if new 'a' is in the old, update 'b' and if old 'a' is not in the new, keep it.</p>

<p>If 'a' is the real key here and b is the value, imo it would be easier to convert the list of dicts into one dict, process the merge and then convert it back. This way you can use the standard functions.</p>

<p>Convert into one dict where a is the key:</p>

<pre><code>def intoRealDict(listOfDicts):
    values = []
    for item in listOfDicts:
        values.append((item.get('a'), item.get('b')))
    return dict(values) #Use Dict Constructur ('3', '4) -&gt; {'3': '4'}
</code></pre>

<p>Convert into the data structure again:</p>

<pre><code>def intoTheDataStructure(realDict):
    res = []
    for i in realDict:
        res.append(dict([('a', i), ('b', realDict[i])]))
    return res
</code></pre>

<p>Easy Merge of your two lists:    </p>

<pre><code>def merge(l1, l2):
    d1, d2 = intoRealDict(l1), intoRealDict(l2)
    for i in d2:
        if i in d1:
            #extend "b"
            d1[i] = d1[i] + ", " + d2[i]
        else:
            #append value of key i
            d1[i] = d2[i]
    return intoTheDataStructure(d1)
</code></pre>

<p>Working Code with bad performance</p>

python list dictionary