update dictionary with dynamic keys and values in python

Remove the following line:

    mydic = {i : o["name"]}

and add the following before your loop:

mydic = {}

Otherwise you’re creating a brand new one-element dictionary on every iteration.

Also, the following:

mydic.update({i : o["name"]})

is more concisely written as

mydic[i] = o["name"]

Finally, note that the entire loop can be rewritten as a dictionary comprehension:

mydic = {i+1:o["name"] for i,o in enumerate(iterload(f))}

Leave a Comment