Home > Enterprise >  I am trying to add entries from list in list to dictionary present in other list
I am trying to add entries from list in list to dictionary present in other list

Time:02-25

a = [ { 1:1 }, {2:2}, {3:3} ] b=[[0,25],[26,51],[52,99]]

I tried doing this:

for item in a:
    for j in range(len(a)):
        item.update( { "st": b[j][0] ,"et": b[j][1]} )
print("a in loop:",a )

getting this output

[{1:1,st:52,et:99},{2:2,st:52,et:99},{3:3,st:52,et:99}]

and I am expecting

[{1:1,st:0,et:25},{2:2,st:26,et:51},{3:3,st:52,et:99}]

CodePudding user response:

You are doing a double loop while you should be looping once.

a = [ { 1:1 }, {2:2}, {3:3} ] 
b=[[0,25],[26,51],[52,99]]
for i,v in enumerate(a):
    v.update( { "st": b[i][0] ,"et": b[i][1]} )
print("a in loop:",a )

Output:

a in loop: [{1: 1, 'st': 0, 'et': 25}, {2: 2, 'st': 26, 'et': 51},
{3: 3, 'st': 52, 'et': 99}]

CodePudding user response:

You need not iterate on both lists, use the index to access the other list and update your dict. Example below

a = [{1: 1}, {2: 2}, {3: 3}]
b = [[0, 25], [26, 51], [52, 99]]
[_dict.update(dict(st=b[index][0],et=b[index][1])) for index, _dict in enumerate(a)]
print(a)

Brings a result:

[{1: 1, 'st': 0, 'et': 25}, {2: 2, 'st': 26, 'et': 51}, {3: 3, 'st': 52, 'et': 99}]

CodePudding user response:

Here you are looping through list a and trying to update list b values by looping with length of list b. Second loop always completes with last value of list b and hence all 'list a' dict will be appended with last element of list b. You can use zip function to iterate 2 list at the same time.

for item1, item2 in zip(a,b):
    item1.update({"st": item2[0], "et": item2[1]})
print("a in loop:",a ) 
  • Related