Jon Doe
Jon Doe

Reputation: 389

Combine two arrays into one JSON

I have array A["a","b","c"] and B[1,2,3]. I am trying to combine them into a single JSON file that has the following structure

[{
    "A": "a",
    "B": 1
  },
  {
    "A": "b",
    "B": 2
  },
  {
    "A": "c",
    "B": 3
  }
]

So far I have tried

data = {}
data['a'] = A
data['b'] = B
json_data = json.dumps(data)
print(json_data)

but that does not produce the result I want.

Any help or ideas are appreciated.

Upvotes: 0

Views: 299

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use zip:

a = ["a","b","c"]
b = [1,2,3]
result = [{'A':c, 'B':d} for c, d in zip(a, b)]

Output:

[{'A': 'a', 'B': 1}, {'A': 'b', 'B': 2}, {'A': 'c', 'B': 3}]

Upvotes: 1

Related Questions