Search code examples
pythonlistdictionarymultiple-entries

Python - dict full of identical values


Really can't get out of this... Here's my python code:

 for i in range(len(realjson)) : 
    store["Store"]={
          "id"          :realjson[i]['id'].strip(),
          "retailer_id" :RETAILER_ID,
          "name"        :find(realjson[i]["title"],">","<").strip(),
          "address"     :realjson[i]["address"].strip(),
          "city"        :realjson[i]["address"].split(",")[-4].strip(),
          "province"    :realjson[i]["address"].split(",")[-3].strip(),
          "group"       :realjson[i]["address"].split(",")[-1].strip(),
          "zip"         :realjson[i]["address"].split(",")[-2].strip(),
          "url"         :"http://blabla.com?id="+realjson[i]["id"].strip(),
          "lat"         :realjson[i]["lat"].strip(),
          "lng"         :realjson[i]["lon"].strip(),
          "phone"       :realjson[i]["telephone_number"].replace("<br />Phone Number: ","").strip()
          }

    stores.append(store)
    print stores[i]

When I print the list inside the for loop it works correctly. Otherwise when I print the array outside the loop like this: print storesit contains only the last element that I've appended repeated for the entire length of the list. Do you have some advice to help me! Thank you.


Solution

  • You reuse a mutable object in your loop:

    store['Store']
    

    Create a new copy in the loop instead:

    newstore = store.copy()
    newstore['Store'] = { ... }