1

I am trying to merge the parent elements with each value item.

The JSON code has the following format:

[
{"id": "1",
"name": "a",
"values": [
    {"ts": 111,
     "speed": 12
    },
    {"ts": 112,
     "speed": 8
    },
]},
{"id": "2",
"name": "b",
"values": [
    {"ts": 113,
     "speed": 10
    },
    {"ts": 114,
     "speed": 7
    },
]}

In the end, the results should look as follows:

[{"id": "1", "name": "a", "ts": 111, "speed": 12},
 {"id": "1", "name": "a", "ts": 112, "speed": 8},
 {"id": "2", "name": "b", "ts": 113, "speed": 10},
 {"id": "2", "name": "b", "ts": 114, "speed": 7}]

My idea was to use two loops. One that loops through all entries and one that loops through "values".

for entry in data:
    for value in entry["values"]:
        # a = entry without "values"
        # a.update(value)
        # print(a)

However, here I have the following problem. How can I get all the values of my entries except "values". I tried to delete "values" from a, however, this resulted in KeyError: 'values' Furthermore, I am not sure if this is actually a good solution to my problem.

I am using python version 3.6.3.

Thanks a lot in advance for any suggestions!

Dannad
  • 189
  • 1
  • 11
  • 1
    I think this question is not related to json. You are working on python data types. I would suggest you leave json out of this question. This makes the question simpler and easier to understand. – guettli Oct 29 '19 at 14:40
  • You're looping through your dict while attempting to alter its keys. Create a temp dict with the changes then update the original one at the end. – slybloty Oct 29 '19 at 14:42

1 Answers1

4

You can build a new list with a nested comprehension to pull out any values you need:

newList = [{'id': d['id'],'name': d['name'], **v} for d in l for v in d['values']]

newList will be:

[{'id': '1', 'name': 'a', 'ts': 111, 'speed': 12},
 {'id': '1', 'name': 'a', 'ts': 112, 'speed': 8},
 {'id': '2', 'name': 'b', 'ts': 113, 'speed': 10},
 {'id': '2', 'name': 'b', 'ts': 114, 'speed': 7}]
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 2
    A slight modification would be `[{**{k: d[k] for k in d if k!= 'values'}, **v} for d in data for v in d['values']]` if you had too many keys to enumerate. – pault Oct 29 '19 at 14:48
  • Thanks @pault, I was just thinking about a nice way to do that. – Mark Oct 29 '19 at 14:49
  • 1
    Side note the `**` syntax to merge the dictionaries is only available in python 3.5+: [How do I merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression) – pault Oct 29 '19 at 14:51