N
N
Ninzalo2022-01-29 20:06:42
Python
Ninzalo, 2022-01-29 20:06:42

How to merge json file elements by parameter?

Hello, I have a json file with a lot of data
example of this file:
[ { "date": "2022-2-7", "other': {more keys} }, { "date": "2022-2-7 ", "other': {more keys} }, { "date": "2022-2-8", "other': {more keys} } ]
I need to combine this data by the "date" key. Sample result:
[ { "date": "2022-2-7", "data": [(here data for the key "other" from all elements with the same date)]},{ "date": "2022-2-8", "data": [(data for key "other" from all elements with the same date here)] } ]
More concrete example:
Input data:
[ { "date": "2022-2-7", "other": {"num": 1, "num2": 2} }, { "date": "2022-2-7", "other": {"num": 3, "num2": 4} }, { "date": "2022-2-8", "other": {"num": 5, "num2": 6} } ]
Result example:
[ { "date": "2022-2-7", "data": [ {"num": 1, "num2": 2}, {"num": 3, "num2": 4} ] }, { "date": "2022-2-8", "data": [ {"num": 5, "num2": 6} ] } ]

I already did something similar before, but it was not very concise and rather cumbersome .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SuperZombie, 2022-01-29
@Ninzalo

It's all right?

arr = [ { "date": "2022-2-7", "other": [123] },
    { "date": "2022-2-7", "other": [456] },
    { "date": "2022-2-8", "other": [789] } ]

new_dict = {}
for i in arr:
  if not i['date'] in new_dict.keys():
    new_dict[i['date']] = i['other']
  else:
    new_dict[i['date']] += i['other']

print(new_dict)

>> {'2022-2-7': [123, 456], '2022-2-8': [789]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question