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