'appending data to a dictionary froma CSV file in a loop

i am reading data from a csv file where i have for example in the columns a name, gender, age...

i want to store this data in a dictionary but the update value clears the previous entries and you can not append to a dictionary...

i have seen that the way to do this would be like this:

Profiles = {}

for rows in data:

    Profile = {'name':rows[0],'gender':rows[1],'age':rows[2]}

    Profiles[entry1] = Profile 
print(Profiles)

file.close()  

how can i loop through this and just have each entry as 1, 2, 3, etc...how do i loop through through?



Solution 1:[1]

That is because you did not change entry value in a loop. By using enumerate(), you can get entry values, such as 0, 1, 2 .... Then, you can use it to keep Profiles updated, as follows:

Profiles = {}
for entry, rows in enumerate(data):
    Profile = {'name': rows[0], 'gender': rows[1], 'age': rows[2]}
    Profiles[entry] = Profile  # so that entry value can be 0, 1, 2 ...  every turn in a loop

print(Profiles)

If you start the entry value from 1 instead of 0, then use list(enumerate(data, 1)) instead of enumerate(data).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Park