Two lists of JSON values -- do operation on some key
<p>I have 2 lists of dictionaries which look like this:</p>

<pre><code>x = [{'id':1,'num':5,'den':8},
     {'id':2,'num':3,'den':5},
     {'id':4,'num':11,'den':18},
     {'id':3,'num':2,'den':81},
     {'id':7,'num':10,'den':33}]

y = [{'id':1,'num':4,'den':9},
     {'id':6,'num':5,'den':11},
     {'id':3,'num':13,'den':83},
     {'id':2,'num':15,'den':28},
     {'id':4,'num':1,'den':2}]
</code></pre>

<p>Now, as it is clear, the keys in each (item) dict of both lists are same. For those elements, which have same <code>id</code>, I want a new list with corresponding <code>num = num(x) + num(y)</code> and <code>den = den(x) + den(y)</code>. So, in this case, output will be:</p>

<pre><code>z = [{'id':1,'num':9,'den':17},
     {'id':2,'num':18,'den':33},
     {'id':4,'num':12,'den':20},
     {'id':3,'num':15,'den':164}]
</code></pre>

<p>How can this be achieved in the most "pythonic" way. Should I just brute force? </p>

<p>a somehow more readable solution : </p>

<pre><code>import collections
result = collections.defaultdict(lambda: {'num': 0,'den': 0})
for data in x + y:
    match = result[data['id']]
    match['num'] += data['num']
    match['den'] += data['den']
    match['id'] = data['id']
z = list(result.values())
</code></pre>

python json list dictionary