0

I am trying to merge two json documents to one, where I need to look for the same "id".

The first document looks like this and is named "mapping"

[{'examine': 'things about 10344',
  'id': 10344,
  'name': 'name10344'},
 {'examine': 'things about 20011',
  'id': 20011,
  'name': 'name20011'},
 {'examine': 'things about 3',
.
.
.

And the second one looks like this. Where 2,6,8 corresponds to the "id" from the first document, and is named "Data"

{'data': {'2': {'avgHighPrice': 159,
   'highPriceVolume': 15541889,
   'avgLowPrice': 153,
   'lowPriceVolume': 7608087},
  '6': {'avgHighPrice': 191833,
   'highPriceVolume': 95,
   'avgLowPrice': 181254,
   'lowPriceVolume': 313},
  '8': {'avgHighPrice': 193657,
   'highPriceVolume': 97,
   'avgLowPrice': 186833,
   'lowPriceVolume': 318},
.
.
.

In the end I would want a document that looks something like this.

[{'examine': 'things about 10344',
  'id': 10344,
  'name': 'name10344'
  'avgHighPrice': 123,
  'highPriceVolume': 123,
  'avgLowPrice': 123,
  'lowPriceVolume': 123},
 {'examine': 'things about 20011',
  'id': 20011,
  'name': 'name20011'
  'avgHighPrice': 123,
  'highPriceVolume': 123,
  'avgLowPrice': 123,
  'lowPriceVolume': 123},
 {'examine': 'things about...',
.
.
.

I tried creating a new directory and adding things to it, but Python wont let me add things to the directory like this.

mydict = {}
x = mapping[0]['id']
mydict[x] = data ['data'][x],mapping[0]
  • Your `data` dict format is wrong. Missing `{`. Fix it and update your question. – 0x0fba Nov 13 '22 at 20:46
  • 1
    I do not understand the correlation between `2, 6, 8` and the `id`. Can you explain with clear examples how these are linked? Remember, the better the question, the better the answer. – Edo Akse Nov 13 '22 at 20:50

1 Answers1

0

If you're sure that there is data for each id in mapping, you can do this:

merged = []
for m in mapping:
    merged.append({**data['data'][str(m['id'])], **m})

It loops through the mapping data to find the corresponding data entry and uses the dict-merge syntax to combine the two. For more on merging dicts, check out this question.

If you don't have data for each mapping, you have to pull the append(...) statement apart and add some validation.

Byted
  • 579
  • 2
  • 12