I have the following lists:
l1 = list(range(10))
l2 = [False for i in range(10)]
I can merge them into a list of dictionaries by implementing the following code:
res = [{l1[i]: l2[i] for i in range(len(l1))}]
My result is the following:
[{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False}]
I would like to repeat the content of the dictionary x
times. For example, if x=2
the res
list would be the following:
[{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False},
{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False}]
My question is how I can define a way to repeat the content of the dictionary based on the x
number and save the result on the res
list.
Thanks
CodePudding user response:
Just expand your comprehension by another loop like this:
N=3
res = [{l1[i]: l2[i] for i in range(len(l1))} for _ in range(N)]
print(res)
[{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False},
{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False},
{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: False,
7: False,
8: False,
9: False}]
CodePudding user response:
You can use zip
to join your 2 lists together, then repeat them with another list comprehension:
l1, l2 = [*range(10)], [False]*10
n = 3
res = [{i1:i2 for i1,i2 in zip(l1,l2)} for _ in range(n)]
CodePudding user response:
res = [{l1[i]: l2[i] for i in range(len(l1))}] * x
CodePudding user response:
You can multiply a list.
res = [{i: False for i in range(10)}] * x