Can anyone tell me how can I get the following output?

Here is my code;

file_name = ['0a57bd3e-e558-4534-8315-4b0bd53df9d8.jpeg', '20d721fc-c443-49b2-aece-fd760f13ff7e.jpeg']
img_id = {}
images = []
for e, i in enumerate(range(len(file_name))):
    img_id['file_name'] = file_name[e]
    images.append(img_id)
print(images)

The output is;

[{'file_name': '20d721fc-c443-49b2-aece-fd760f13ff7e.jpeg'}, {'file_name': '20d721fc-c443-49b2-aece-fd760f13ff7e.jpeg'}]

I want it to be;

[{'file_name': '0a57bd3e-e558-4534-8315-4b0bd53df9d8.jpeg'}, {'file_name': '20d721fc-c443-49b2-aece-fd760f13ff7e.jpeg'}]

I don't know, why it is saves only the last file name in the dictionary?

Topic python

Category Data Science


You are overwriting the data stored in img_id because you are using the same dictionary with the same key (file_name). You can either reset the img_id variable to an empty dictionary within your for loop or use a simpler list comprehension:

file_name = ['0a57bd3e-e558-4534-8315-4b0bd53df9d8.jpeg', '20d721fc-c443-49b2-aece-fd760f13ff7e.jpeg']

images = []
for e, i in enumerate(range(len(file_name))):
    img_id = {}
    img_id['file_name'] = file_name[e]
    images.append(img_id)

# or
[{"file_name": x} for x in file_name]

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.