Jazz
Jazz

Reputation: 475

Iterate list and dictionary at the same time Python

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

Answers (2)

Boseong Choi
Boseong Choi

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

Dewald Abrie
Dewald Abrie

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

Related Questions