pythonfiledictionarytkinter

How do I store dictionaries in a file and read/write that file?


I am using tkinter to manage the GUI for a note retrieval program. I can pull my notes by typing a key word and hitting Enter in a text field but I would like to move my dictionary to a file so that my code space is not filled up with a massive dictionary.

I have been looking around but I am not sure how I would go about doing this. I have the file in my directory. I know I can use open(“filename”, “mode”) to open said file for reading but how do I call each section of the notes.

For example what I do now is just call a keyword from my dictionary and have it write the definition for that keyword to a text box in my GUI. Can I do the same from the file?

How would I go about reading from the file the keyword and returning the definition to a variable or directly to the text box? For now I just need to figure out how to read the data. I think once I know that I can figure out how to write new notes or edit existing notes.

This is how I am set up now.

To call my my function

root.bind('<Return>', kw_entry)

How I return my definition to my text box

def kw_entry(event=None):
    e1Current = keywordEntry.get().lower()
    if e1Current in notes:
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, notes[e1Current])
        root.text.see(tkinter.END)
    else:
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, "Not a Keyword")
    root.text.see(tkinter.END)

Solution

  • Sound's like you'd need to load the dictionary to memory at init time, and use it like a normal dictionary.

    I am assuming your dictionary is a standard python dict of strings, so I recommend using the python json lib.

    Easiest way to do this is to export the dictionary as json once to a file using something like:

    with open(filename, 'w') as fp:
        json.dump(dictionary, fp)
    

    and then change your code to load the dict at init time using:

    with open(filename) as fp:
        dictionary = json.load(fp)
    

    Alternatively, if your data is more complex than text, you can use python shelve which is a persistent, dictionary-like object to which you can pass any pickle-able object. Note that shelve has its drawbacks so read the attached doc.