Home > database >  Why does this for loop loop twice?
Why does this for loop loop twice?

Time:11-25

This is what I'm trying to accomplish:

list_dic_gen(['One','Two'], [['First','Second']])

is

[{'One': 'First', 'Two': 'Second'}]

As a second example of this, the function call:

list_dic_gen(['Second'], [['One'],['Third Fourth']])

would be expected to return:

[{'Second': 'One'}, {'Second': 'Third Fourth'}]

But my code

def list_dic_gen(lst,lol):
 acc=[]
 a=0
 for x in lol:
   accd={}
   for b in x:
     accd[lst[a]]=b
     acc.append(accd)
     if len(lst)>1:
       a =1
 return acc

This code works for the second example, but for the first example, the for loop makes 2 dictionaries even though there is 1 list in the list

[{'One': 'First', 'Two': 'Second'}, {'One': 'First', 'Two': 'Second'}]

CodePudding user response:

Because there are 2 b's in x and you are appending for both. Append acc after the inner loop.

def list_dic_gen(lst,lol):
    acc=[]
    a=0
    for x in lol:
        accd={}
        for b in x:
          accd[lst[a]]=b
          a  = len(lst)>1 #you don't need a condition
        acc.append(accd)  #append the list after the loop
    return acc

print(list_dic_gen(['One','Two'], [['First','Second']]))

I believe my complete refactor of your function does the same thing that yours does. I don't have enough test cases to be positive.

def list_dic_gen(keys:list, data:list) -> list[dict]:
    return [{keys.pop(0):value for value in values} for values in data]
  • Related