When filling in a python dictionary in for me, repeat the last value in the other items

1

I have a dictionary that I want to fill with two lists, one that has the key and another that has the values, when it is with the for to save each item it is removed in order and saves them, but at the time of printing the dictionary I see that the last value is repeated in all the items

arreglo = [1,2,3,4,5,6]
arreglo_2 = ['aguilas', 'tigres', 'leones', 'estrellas', 'gigantes', 'toros', ]
EQUIPOS_DICT = {}

for a in arreglo:
    for a2 in arreglo_2:
        print 'Se guardara %s' % (a2)
        EQUIPOS_DICT[str(a)] = a2

EQUIPOS = EQUIPOS_DICT.items()

print EQUIPOS

SALIDA> 
[('1', 'toros'), ('3', 'toros'), ('2', 'toros'), ('5', 'toros'), ('4', 'toros'), ('6', 'toros')]
    
asked by Wildy Estephan 11.10.2017 в 18:58
source

1 answer

0

The problem is this code:

for a in arreglo:
    for a2 in arreglo_2:

For each key you go through all the values every time, so each time you do: EQUIPOS_DICT[str(a)] = a2 you are updating the value of the key str(a) , so that in the end you always keep the last value.

The solution is very simple, you can do this:

EQUIPOS = dict(zip(arreglo, arreglo_2))
print(EQUIPOS)

And the output you would get:

[('1', 'aguilas'), ('3', 'leones'), ('2', 'tigres'), ('5', 'gigantes'), ('4', 'estrellas'), ('6', 'toros')]

What we do is use zip() to "map" each value in a list with the one of the other, generating "tuples", for example: (1, 'aguilas'), (2, 'tigres)... , and with dict we build the dictionary from these tuples. One condition, is that both lists have the same amount of values, we could eventually map a list of keys with a smaller list of values but we should use zip_longest()

If you eventually want to use the basic form, using a cycle for , the correct form would be this:

i = 0
for a in arreglo:
  EQUIPOS_DICT[str(a)] = arreglo_2[i]
  i = i + 1
    
answered by 11.10.2017 / 19:09
source