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>You may achieve it using <code>list comprehension</code> as:</p>

<pre><code>&gt;&gt;&gt; [{'id': i['id'], 'num': i['num'] + j['num'], 'den': i['den'] + j['den']} for i in x for j in y if i['id'] == j['id']]
[{'num': 9, 'id': 1, 'den': 17}, {'num': 18, 'id': 2, 'den': 33}, {'num': 15, 'id': 3, 'den': 164}, {'num': 12, 'id': 4, 'den': 20}]
</code></pre>

python json list dictionary