vish4071 vish4071 - 1 year ago 42
JSON Question

Two lists of JSON values -- do operation on some key

I have 2 lists of dictionaries which look like this:

x = [{'id':1,'num':5,'den':8},

y = [{'id':1,'num':4,'den':9},

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

z = [{'id':1,'num':9,'den':17},

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

Answer Source

You may achieve it using list comprehension as:

>>> [{'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}]