How do I keep a dictionary so I do not lose its content?

1

I was creating a simple program to review words in English and I had a question.

How can I save the words entered in the dictionary created for a future session? . When you close the program and reopen, all the words in the dictionary are deleted.

I tried to save it in a file.txt but at the time of reading the file to extract the dictionary it gives many problems.

Could you save the generated cache in the session and run it again the next time you load the program to not lose the dictionary?

Or maybe you could use a library or some other option that I do not know?

I would like it to be in a file and not resort to databases like MySQL.

#!/bin/python3
# -*- coding: utf-8 -*-

def repasar():
    while True:
        for d in x:
            print ("palabra: %s" %(d))
            ing = input("Escribe en ingles: ")

            if ing == dic.get(d):
                print ("correcto")
            else:
                print ("Incorrecto: %s" %(ing))

def agregar():
    x=input("Palabra en español: ")
    y=input("Palabra en ingles: ")
    dic[x]=y
    print (dic)

dic={}

print ("1. Repasar")
print ("2. Añadir palabra")
decision = input("Que quieres hacer? ")


if decision == "1":
    repasar()
elif decision == "2":
    agregar()

PS: I put the program in case it is necessary to find a solution. You can see that it is unfinished, I left it like that until I found a solution to the aforementioned problem.

    
asked by Mike 09.05.2017 в 23:16
source

1 answer

4

If you do not want to use databases ( sqlite is included in the standard library and is very easy to use) you can use pickle or cpickle to serialize Python objects.

This way you save the dictionary in a file and when you start your program you load it. This way you avoid reading and manually parsing a txt or csv to build your dictionary.

I have taken the liberty of modifying some other things in your code but the idea of using pickle is in two functions:

  • cargar_datos() : try to open the data file ( traducciones.dat ). If it exists it loads it and returns the dictionary of the previous session. If it does not exist, it returns an empty dictionary.

  • guardar_datos() : use pickle.dump() to save the current dictionary so it is available in future sessions.

The code would be:

#!/bin/python3
# -*- coding: utf-8 -*-

import pickle


def repasar(dic):
    for es, ing in dic.items():
        resp = input('Escribe en ingles "{}": '.format(es))
        if resp == ing:
            print ("Correcto.")
        else:
            print ('Incorrecto, es "{}".'.format(ing))

def agregar(dic):
    x = input("Palabra en español: ")
    y = input("Palabra en ingles: ")
    dic[x] = y

def cargar_datos():
    try:
        with open("traducciones.dat", "rb") as f:
            return pickle.load(f)
    except (OSError, IOError) as e:
        return dict()

def guardar_datos(dic):
    with open("traducciones.dat", "wb") as f:
        pickle.dump(dic, f)


def main():
    dic = cargar_datos()
    menu ='''
    1. Repasar.
    2. Añadir palabra.
    3. Guardar y salir.
    '''

    while True:
        print(menu)
        decision = input("¿Que quieres hacer?: ")
        if decision == "1":
            repasar(dic)
        elif decision == "2":
            agregar(dic)
        elif decision == "3":
            guardar_datos(dic)
            break
        else:
            print('Opción inválida, intentelo de nuevo.')

if __name__ == '__main__':
    main()

The sqlite3 option is much more efficient if you are going to end up with very large dictionaries. The most 'basic' option is to use a txt or csv and build with the dictionary. You could help from the module csv for that, but I'll leave that to your choice.

    
answered by 10.05.2017 / 00:24
source