vish4071 vish4071 - 2 months ago 7
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},
{'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}]


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

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}]


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

Answer

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}]