Home > OS >  How to create list of dictionaries from merging two lists together, where the keys are repeated
How to create list of dictionaries from merging two lists together, where the keys are repeated

Time:01-04

I have two lists:

lst = [1.1, 1.1, 1.1, 1.1]

keys = [[2, 3, 1, 4], [2, 1, 4, 3], [3, 1, 2, 4], [3, 2, 4, 1]]

I would like to create a list of dictionaries and output:

d = [{2: 1.1, 3: 1.1, 1: 1.1, 4: 1.1}, {2: 1.1, 1: 1.1, 4: 1.1, 3: 1.1}, {3: 1.1, 1: 1.1, 2: 1.1, 4: 1.1}, {3: 1.1, 2: 1.1, 4: 1.1, 1: 1.1}]

I have tried d = [dict(zip(keys, i)) for i in lst]

but this returns TypeError: zip argument #2 must support iteration

Any help appreciated

CodePudding user response:

You need to iterate over the keys:

l = [1.1, 1.1, 1.1, 1.1]
keys = [[2, 3, 1, 4], [2, 1, 4, 3], [3, 1, 2, 4], [3, 2, 4, 1]]
d = [dict(zip(i, l)) for i in keys]
print(d)

Output:

[{2: 1.1, 3: 1.1, 1: 1.1, 4: 1.1}, {2: 1.1, 1: 1.1, 4: 1.1, 3: 1.1}, {3: 1.1, 1: 1.1, 2: 1.1, 4: 1.1}, {3: 1.1, 2: 1.1, 4: 1.1, 1: 1.1}]

CodePudding user response:

For each element d in keys, you want to create a dictionary created by zipping each element of l with d, so

[dict(zip(d, l)) for d in keys]
  •  Tags:  
  • Related