I’m trying to merge two lists to dict:
JavaScript
x
3
1
l1 = [1, 3, 6, 0, 1, 1]
2
l2 = ['foo1', 'foo2', 'foo1', 'foo2', 'foo2', 'bar1']
3
I’d like to get:
JavaScript
1
7
1
list = [{"foo1": 1},
2
{"foo2": 3},
3
{"foo1": 6},
4
{"foo2": 0},
5
{"foo2": 1},
6
{"bar1": 1},]
7
trying to use zip but get an error :”<zip object at 0x000>”
Advertisement
Answer
You can try this:
JavaScript
1
7
1
l1 = [1, 3, 6, 0, 1, 1]
2
l2 = ['foo1', 'foo2', 'foo1', 'foo2', 'foo2', 'bar1']
3
4
data = [{k: v} for k, v in zip(l2, l1)]
5
6
print(data)
7
Output:
JavaScript
1
2
1
[{'foo1': 1}, {'foo2': 3}, {'foo1': 6}, {'foo2': 0}, {'foo2': 1}, {'bar1': 1}]
2
I wouldn’t consider this an ideal data structure though, unless you have a lot more data in the individual dictionaries.