3

Creating a list of dictionaries via a for loop

I've been trying to create a list of dictionaries via a for loop, code shown below

a=["x","y","z"]
b=[1,2,3]
dict1={}
superlist=[]
for i in range(0,len(a)):
    dict1['name']=a[i]
    dict1['values']=b[i]
    superlist.append(dict1)

What I'm expecting as my output is [{'name':'x', 'values':1},{'name':'y', 'values':2},{'name':'z', 'values':3}],

instead I get

[{'name':'z', 'values':3},{'name':'z', 'values':3},{'name':'z', 'values':3}].

I'm not really sure what's going on here and it'd be great if someone can explain and help me get my desired result.

S C
  • 167
  • 1
  • 2
  • 5
  • Keys are _unique_ - you can add it only once. If you add it new, it overwrites the last value of the key. You add `'name'` three times - only the last value sticks. You use the same dictionary - if you move your `dict1={}` _inside_ the loop you create new dicts and do not add the same ref multiple times to your masterlist. The problem is the same as the dupe, both are muteable datatypes that are references to its data – Patrick Artner Apr 05 '19 at 18:02
  • @PatrickArtner really *not* a good duplicate, at least for a new – Grijesh Chauhan Apr 05 '19 at 18:05
  • @GrijeshChauhan Why? It is the same reason. He is adding the same reference to his superlist - (1. problem) and he is modifying the same dictionary over and over (2. problem). Do you know a good dupe that is similar to mine just with dicts instead of lists? – Patrick Artner Apr 05 '19 at 18:07
  • 1
    @Grije I added a second duplicate for the second problem this code has. Together with the already given answer this should be enough to help him out. – Patrick Artner Apr 05 '19 at 18:12
  • @PatrickArtner perfect. – Grijesh Chauhan Apr 05 '19 at 18:13

1 Answers1

7

You are appending a reference to dict1 on each iteration, but you are also changing the values of the keys each time so that when you end you have a list of references to the same dict (which is why they all look the same).

Simple fix is to move dict1 = {} inside your for loop. That way you are creating a new dict with its own key value pairs to be appended on each iteration.

benvc
  • 14,448
  • 4
  • 33
  • 54