Nobi
Nobi

Reputation: 1109

Adding items to a dictionary from a list

please how can I add new values to the pos dictionary using the items in j as key and those in z as values

j = [3,5]
z = [(560,848), (833,934)]
pos = {2:(545,577), 4:(465,799)}

I tried

for i in z:
    pos[j] = z[i]

but it gives this error: TypeError: list indices must be integers, not tuple.

Thanks

Upvotes: 0

Views: 42

Answers (2)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5693

Use zip to create pairs that you can then convert into a dict. E.g.

pos = dict(zip(j, z))

If you want it more explicit that would be

pos = {}
for key, value in zip(j,z) :
    pos[key] = value

Upvotes: 1

shx2
shx2

Reputation: 64318

It seems like you want to iterate over j as well.

zip is useful for iterating over two (or more) lists:

for jj, zz in zip(j, z):
  pos[jj] = zz

Upvotes: 0

Related Questions