0
$\begingroup$

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?

$\endgroup$

1 Answer 1

2
$\begingroup$

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]
$\endgroup$
1
  • $\begingroup$ hahha, how can I miss that!!! Thank you $\endgroup$ May 17, 2022 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.