Add new element to Python dictionary

2

I want to add new elements to a dictionary in a for cycle, but it is replaced. I am adding it this way:

   for j in range(len(Repetidos)): 
         historias[m[j]]=Repetidos[j]

Is it okay how I do it? since at the end I only throw an element for each key of the dictionary, the idea is that each key contains several elements. Or it must be done with "append"

Greetings!

    
asked by Jorge Ponti 13.07.2017 в 00:47
source

1 answer

3

By doing this you are replacing (reassigning) the value of the key in each iteration, so in the end you will only have the last value, corresponding to: m[len(repetidos)-1] .

To add new values you will need to use a list as a value and use append as you say:

historias[m[j]].append(Repetidos[j])

If you do this you must define an empty list previously as a value to each dictionary key. You must do this once and before adding any value to the list:

historias[m[j]] = []

A more convenient option is to use collections.defaultdict . When you create stories you do it this way:

from collections import defaultdict

historias = defaultdict(list)

Now every time you create a new key, an empty list is created as a value automatically. So you do not have to worry about using the append method on a list that does not exist.

for j in range(len(Repetidos)): 
     historias[m[j]].append(Repetidos[j])
    
answered by 13.07.2017 / 01:01
source