Mahir Islam
Mahir Islam

Reputation: 1972

How to use two nested lists to make a list of dictionaries?

I have two nested nested lists, like this one:

list_1 = [[100, 90, 90, 85, 70], [100, 90, 90, 85, 80], [105, 100, 90, 90, 85]]
list_2 = [[1, 2, 2, 3, 4], [1, 2, 2, 3, 4], [1, 2, 3, 3, 4]]

I want to use the elements in list_1 with list_2 to make a dictionary but it needs to be in the form of a nested list, the output should be like this:

[{100:1,90:2,90:2,85:3,70:4},{100:1,90:2,90:2,85:3,80:4},{105:1,100:2,90:3,90:3,85:4}]

Is there any way in Python 3 to do this?

Upvotes: 1

Views: 599

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

Another approach:

list(map(dict, map(zip, list_1, list_2)))

Which I find very pleasing.

Upvotes: 4

wim
wim

Reputation: 362488

I think you want to zip zips:

>>> [dict(zip(*z)) for z in zip(list_1, list_2)]
[{70: 4, 85: 3, 90: 2, 100: 1},
 {80: 4, 85: 3, 90: 2, 100: 1},
 {85: 4, 90: 3, 100: 2, 105: 1}]

Or maybe you wanted strings, keeping duplicate "keys":

>>> [[f'{a}:{b}' for a,b in zip(*z)] for z in zip(list_1, list_2)]
[['100:1', '90:2', '90:2', '85:3', '70:4'],
 ['100:1', '90:2', '90:2', '85:3', '80:4'],
 ['105:1', '100:2', '90:3', '90:3', '85:4']]

Upvotes: 10

Related Questions