Tuple FOR loop inside other tuple

Asked

Viewed 67 times

1

I’m trying to run a loop of tuples inside another tuple. When I run the application it just returns me the last tuple.

minha_tupla = (('willian','123','25.26'),('carla','654','45.58'))

titulos = ('nome','cod','valor')
meu_dic = {}

for x in range(0,len(minha_tupla)):
    for t in range(0,len(titulos)):
        meu_dic[titulos[t]] = minha_tupla[x][t]

print(meu_dic)
  • Your problem is with the bow for and the reference. You are not creating a new record with each iteration, but only changing the items. In other words you pass the values of the first tuple in the 1st loop of the for and then overwrite the same values with the data passed by the second for. I suggest creating a list of dictionaries.

1 answer

2


The problem is that the dictionary is overwritten with each iteration. In the first iteration, for example, you set the name to "Willian", and in the second iteration the name is set to "Carla", overriding the previous value.

If you want each record to correspond to a dictionary, then you must create a new one at each iteration, and save them in another structure, such as a list:

minha_tupla = (('willian','123','25.26'),('carla','654','45.58'))
titulos = ('nome','cod','valor')
valores = [] # lista que irá ter os dicionários 
for dados in minha_tupla:
    valores.append(dict(zip(titulos, dados))) # adicionar novo dicionário
 
print(valores)

Notice you don’t need range to iterate, you can use for elemento in tupla to have its own element.

And you also don’t need to create the keys one by one. Just use zip, that goes through the titles and the respective values, so the dictionary is already created correctly.

The result is a list of dictionaries, with each dictionary corresponding to one of the original tuples:

[{'nome': 'willian', 'cod': '123', 'valor': '25.26'},
 {'nome': 'carla', 'cod': '654', 'valor': '45.58'}]

And if you want, you can change the for above by a comprehensilist on:

valores = [ dict(zip(titulos, dados)) for dados in minha_tupla ]
  • 1

    Brother, that’s right... Oh man, thank you very much. Ball show. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.