-3

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>"

3 Answers3

4

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.

bherbruck
  • 2,167
  • 1
  • 6
  • 17
2

The answer by @Tenacious B achieves what you requested.

You might, however, be better with a dictionary of lists. The keys would be items from l2 and values would be a list containing the corresponding values from l1. A collections.defaultdict makes this easy:

l1 = [1, 3, 6, 0, 1, 1]
l2 = ['foo1', 'foo2', 'foo1', 'foo2', 'foo2', 'bar1']

from collections import defaultdict

d = defaultdict(list)
for k, v in zip(l2, l1):
    d[k].append(v)

print(d)

Output:

defaultdict(, {'foo1': [1, 6], 'foo2': [3, 0, 1], 'bar1': [1]})

Now you can access the data by key:

>>> d['foo2']
[3, 0, 1]
>>> d['foo1']
[1, 6]
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

I'm pretty sure <zip object at 0x0000021A9C9F71C0> is not an error, you just haven't execute the code yet. It is stored in a zip object which is waiting for execution.