0

So, I am trying to achieve the following. I have a json with following structure:

json = {'key1':[value11,value12], 'key2':[value12, value22]}

I want to separate each value in particular key to from a separate json while retaining its key as follows:

json1 = {'key1':value11,'key2':value12}
json2 = {'key1':value12,'key2':value22}

Builtin json module does not seems to help

7
  • Do all the lists have the same length? What happens, if they don't have? Commented Nov 18, 2019 at 9:38
  • They always always have same length. Incase they don't, then logically the later jsons values should be None Commented Nov 18, 2019 at 9:41
  • Perhaps you want a list of those dict objects instead of separate variables? Commented Nov 18, 2019 at 9:45
  • Even that would be good enough Commented Nov 18, 2019 at 9:53
  • [{key:json[key]} for key in json.keys()] shouldn't this be enough? Commented Nov 18, 2019 at 10:05

1 Answer 1

1

Its hacky and I could not figure out to use the inline for loops, but it works for me: I first created the empty array, and due to the for loops you should be able to catch the case if sth should be none...

json = {'key1':[11, 12], 'key2':[21, 22]}
max_len = max([len(json[key]) for key in json.keys()])
data = [{}] * max_len
# data = [{} for _ in range(max_len)]
for i in range(max_len):
    for key in json.keys():
        data[i][key] = json[key][i] if json[key][i] else None
print(data)

gives:

[{'key1': 11, 'key2': 21}, {'key1': 12, 'key2': 22}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.