You can do this with zip
, which combines two lists which can then be converted to a dict
. You can do this in one line with list comprehension.
first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
print([dict(zip(first, item)) for item in second])
# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]
Without list comprehension:
first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
result = []
for item in second:
result.append(dict(zip(first, item)))
print(result)
# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]
And a little bit more code, using enumerate
:
first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
result = []
for sub in second:
d = {}
for index, item in enumerate(first):
d[item] = sub[index]
result.append(d)
print(result)
# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]