Reputation: 475
I have a list of dictionary(k) and a list(l)
k = [
{'x': 2.5, 'y': 1.5, 'z': 2},
{'x': 3, 'z': -1.5},
]
l = [-9, -2, -4, 1, 4, 7]
What will be the easiest way to iterate k and z so together so that we can compute a formula for example using these values?
So far I have been using:
for dic in k:
for key in dic:
print(dic[key])
But this only iterates k
alone. I need both k
and z
to iterate together so that we can use subsequent values to compute a function.
Output expected to compute a function for every values:
x + y*l + z*l*l
x,y,z
will be 0
where it is not present
Upvotes: 0
Views: 553
Reputation: 2596
import itertools
k = [
{'x': 2.5, 'y': 1.5, 'z': 2},
{'x': 3, 'z': -1.5},
]
l = [-9, -2, -4, 1, 4, 7]
for d, i in itertools.zip_longest(k, l, fillvalue={}):
x = d.get('x', 0)
y = d.get('y', 0)
z = d.get('z', 0)
print(x + y*i + z*i*i)
output:
151.0
-3.0
0
0
0
0
constraint: l
has to always be longer than k
.
Upvotes: 2
Reputation: 1492
Try this
for dic, l in zip(k, z):
x, y, z = dic.get(‘x’, 0), dic.get(‘y’, 0), dic.get(‘z’, 0)
return x + y*l + z*l*l
Upvotes: 0