Write dictionary in text file

0

Hello, I am trying to write a dictionary, with name and phone data, in a text file and I can not achieve it. My dictionary is of the type: agenda = {"Juan": 14253, "Mariano": 24875, "Marcos": 65232} and what I did was this:

agenda={"Juan":14253 , "Mariano": 24875 , "Marcos":65232}
agendaarchivo=open("agendaarchivo.txt", "w")
for nombre,agenda[nombre] in agenda:
    agendaarchivo.write(nombre+":"+agenda[nombre]+"\n")

agendaarchivo.close()

And I miss the following error:

Traceback (most recent call last):
File "C:\Users\Usuario\Desktop\final compu\error\prue.py", line 4, in 
<module>
for nombre,agenda[nombre] in agenda:
ValueError: too many values to unpack (expected 2)
    
asked by Estanislao Ortiz 10.12.2017 в 21:13
source

1 answer

0

You must iterate through. items() , this returns the key and the value.

agenda={"Juan":14253 , "Mariano": 24875 , "Marcos":65232}
with open("agendaarchivo.txt", "w") as agendaarchivo:
    for nombre, valor  in agenda.items():
        agendaarchivo.write("%s %s\n" %(nombre, valor))
    
answered by 10.12.2017 / 21:21
source