Atirag Atirag - 28 days ago 4
Python Question

Python: Looping through a list of dictionaries and extracting values to a new dictionary

I need to loop on a list of dictionaries and check if a value exist. If it exists then I take another value from this same dictionary and store it on a new dictionary inside another list. What I have is this

for root, dirs, files in os.walk(files_path+"/TD"):
for file in files:
for d in data_list:
if d['id'] == file_name:

So I loop through some files. data_list is a list of dictionaries. These dictionaries each have an 'id' which matches a file name so when the dictionary 'd' with the value 'id' is found I take the value of 'fic' on dictionary 'd' and make a new dictionary with the key 'class' to store the value of 'fic'. Then I store this dictionary on a new list of dictionaries called class_copy.

The problem is that after looping through all, all the dictionaries in class_copy are the same. I guess that by looping and changing the instance of d the values on class_copy are also changing but how could I retain the values? Is there a better way to do this?


You are not actually creating a new dictionary, you are updating an existing one:


simply updates the value associated with the key 'class'. Change your code to this:

cc = {'class': d['fic']}

which will create a new instance of a dictionary.

The reason that all entries in your list end up being the same is because each item in the list is the same dictionary. By creating a new dictionary as shown you will have independent instances in the list as you were expecting.