Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this for loop loop twice?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}]

>Solution :

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.

def list_dic_gen(keys, data) -> list[dict]:
    return [{keys.pop():value for value in values} for values in data]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading