Reputation: 1690
I am running a script that extracts data into dictionaries, it creates new parameters with the old ones and then it has to append the new parameters to a list.
The loop goes well, every time I print parameters, it updates the values correctly and creates a new value, new url, everything fine.
The issue comes when I append parameters to the image_data_list. It does not add the new dictionary to the list, but it transform every value in the list into the new one, so I get lists of 200 equal dictionaries when I need a list of different dictionaries that I get in every iteration.
image_data_list = []
status = True
index = 1
sd.click_image()
while status:
try:
all_urls = sd.extract_images()
parameters = sd.get_parameters(parameters_)
for url in all_urls:
parameters["url"] = url
parameters["index"] = index
print(parameters)
image_data_list.append(parameters)
print(image_data_list)
index += 1
except TimeoutException:
status = False
print("Ending Execution due to Timeout Exception")
break
How con I avoid this type of results:
[{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url.jpg', 'index': 4}]
And get something like:
[{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' blue lips', 'url': 'image_url_1.jpg', 'index': 1},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' brown eyes', 'url': 'image_url_2.jpg', 'index': 2},
{'age': 'adult', 'gender': 'female', 'ethnicity': 'latino', 'title': ' caramel', 'url': 'image_url_3.jpg', 'index': 3}]
The final result must be a list of dictionaries with all different values per iteration, every new gets appended but old ones should not change
Upvotes: 0
Views: 62
Reputation: 413
u could try this,see if it's work
import copy
image_data_list = []
status = True
index = 1
sd.click_image()
while status:
try:
all_urls = sd.extract_images()
parameters = sd.get_parameters(parameters_)
for url in all_urls:
copyed_parameters = copy.deepcopy(parameters)
copyed_parameters["url"] = url
copyed_parameters["index"] = index
image_data_list.append(copyed_parameters)
index += 1
except TimeoutException:
status = False
print("Ending Execution due to Timeout Exception")
break
Upvotes: 1