I want to add new items to a dictionary in a for loop, but it gets replaced. I'm adding it like this:
for j in range(len(Repetidos)):
historias[m[j]]=Repetidos[j]
Is it okay how I do it? since in the end it throws me only one element for each dictionary key, the idea is that each key contains several elements. Or should it be done with "append"
Cheers!
By doing that you are replacing (reassigning) the value of the key in each iteration, so in the end you will only have the last value, the one corresponding to :
m[len(repetidos)-1]
.To add new values you will need to use a list as value and use
append
as you say:If you do this you must define a previously empty list as a value to each key in the dictionary. You must do this only once and before adding any value to the list:
A more comfortable option is to use
collections.defaultdict
. When you create stories you do it this way:Now every time you create a new key an empty list is created as a value automatically. So you don't have to worry about using the method
append
on a list that doesn't exist.