-1

I'm trying to map two arrays together to a list of dictionaries. Like this:

a_list = [1, 2, 3]
b_list = ["a", "b", "c"]

d = [{"key1": a, "key2": b} for a in a_list for b in b_list]
>> [{"key1": 1, "key2": "a"}, {"key1": 2, "key2": "b"}, {"key1": 3, "key2": "c"}]

However, this gives:

[{"key1": 1, "key2": "a"}, {"key1": 1, "key2": "b"}, [...] {"key1": 3, "key2": "b"}, {"key1": 3, "key2": "c"}]

I've tried replacing the second forwith both and and a ,, as well as moving parts off the code into parentheses back and forth.

ntoonio
  • 3,024
  • 4
  • 24
  • 28

1 Answers1

2

use zip

a_list = [1, 2, 3]
b_list = ["a", "b", "c"]
d = [{"key1": a, "key2": b} for (a, b) in zip(a_list, b_list)]
print(d)  # [{'key1': 1, 'key2': 'a'}, {'key1': 2, 'key2': 'b'}, {'key1': 3, 'key2': 'c'}]
xashru
  • 3,400
  • 2
  • 17
  • 30