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 ]
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 thefor
and then overwrite the same values with the data passed by the secondfor
. I suggest creating a list of dictionaries.– Evilmaax