1
import pandas as pd
from pandas import DataFrame

words = {}

def add_word():
    ask = input("Do You Want To Add a New Word?(y/n): ")
    if ask == 'y':
        new_word = input("type the word you want to add: ")
        word_meaning = input("type the word meaning: ")
        words[new_word] = [word_meaning]

    elif ask == 'n':
        pass


add_word()

table = pd.DataFrame(data=words)
table_transposed = table.transpose()
print(table_transposed)

as you can see, i want to make a dictionary but i don't know how to save the user's input. i want to take the user input and save it in the dictionary, so the next time he uses the program he can see everything he added before

  • 1
    It seems like you **did** add it to the dictionary. What exactly is the problem? – Tomerikoo Jun 03 '20 at 13:00
  • 1
    Do you mean something like this: https://stackoverflow.com/questions/17179222/python-saving-data-outside-of-program ? – Tomerikoo Jun 03 '20 at 13:04
  • i think so but in my case what should i write, i am sorry i am new to this – Omar Khaled Jun 03 '20 at 13:21
  • yeah i am adding it to the dictionary but it disappears when i run the program again. – Omar Khaled Jun 03 '20 at 13:29
  • Ok, of course. Whenever you run the program it has a new state. If you want to preserve state between runs, this is a duplicate question and has many answers already. Like the ones in the link I provided... More: https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file/32216025 ; https://stackoverflow.com/questions/7100125/storing-python-dictionaries – Tomerikoo Jun 03 '20 at 13:40

2 Answers2

1

When you make and populate (fill) a dictionary in a running Python program, that dictionary only exists as long as the program is running. When you close the program - that memory is wiped and any modifications that are made are not stored.

As Tomerikoo pointed out, this solution: shelving dictionaries will allow you to preserve your dictionary after the program is closed. I copy the code from the link (jabaldonedo's solution) and annotate it for you for clarity.

import shelve  # this is a Python library that allows you to store dictionaries after the program is closed
data = {'foo':'foo value'}  # this is a mock-up dictionary. "words" in your case
d = shelve.open('myfile.db')  # this creates a storage container in the program folder that can store multiple dictionaries. You can see this file appear when this code runs.
d['data'] = data  # you make a section in that storage container, give it a name, e.g. "data" in this case, and store your dictionary in that section. You will store your "words" here.
d.close() # close the storage container if you do not intend to put anything else inside.

When you close and open up the program, the dictionary will not automatically pop into your running memory - you need to write code to access it. It can be made as an option in your game menu, e.g. "Load existing dictionary of words".

Back to jabaldonedo's solution:

import shelve  # no need to import again, if you are writing in the same python program, this is for demonstration
d = shelve.open('myfile.db')  # open the storage container where you put the dictionary
data = d['data']  # pull out the section, where you stored the dictionary and save it into a dictionary variable in the running program. You can now use it normally.
d.close() # close the storage container if you do not intend to use it for now.

EDIT: Here is how this could be used in the specific context provided in your answer. Note that I imported an additional library and changed the flags in your shelve access commands.

As I mentioned in my comment, you should first attempt to load the dictionary before writing new things into it:

import shelve
import dbm  # this import is necessary to handle the custom exception when shelve tries to load a missing file as "read"


def save_dict(dict_to_be_saved):  # your original function, parameter renamed to not shadow outer scope
    with shelve.open('shelve2.db', 'c') as s:  # Don't think you needed WriteBack, "c" flag used to create dictionary
        s['Dict'] = dict_to_be_saved  # just as you had it


def load_dict():  # loading dictionary
    try:  # file might not exist when we try to open it
        with shelve.open('shelve2.db', 'r') as s:  # the "r" flag used to only read the dictionary
            my_saved_dict = s['Dict']  # load and assign to a variable
            return my_saved_dict  # give the contents of the dictionary back to the program
    except dbm.error:  # if the file is not there to load, this error happens, so we suppress it...
        print("Could not find a saved dictionary, returning a blank one.")
        return {}  # ... and return an empty dictionary instead


words = load_dict()  # first we attempt to load previous dictionary, or make a blank one

ask = input('Do you want to add a new word?(y/n): ') 
if ask == 'y':
    new_word = input('what is the new word?: ')
    word_meaning = input('what does the word mean?: ')
    words[new_word] = word_meaning
    save_dict(words)
elif ask == 'n':
    print(words)  # You can see that the dictionary is preserved between runs
    print("Oh well, nothing else to do here then.")


KIO
  • 61
  • 6
  • tanks a lot for your help, i understood a lot about shelve and i tried a couple of examples, but i am not sure about how can i use it in my code, because of the above function i am confused. – Omar Khaled Jun 03 '20 at 20:14
  • Make a function that will take in your dictionary as parameter. This function, let's say you call it `save_dict`, will save the dictionary using the `shelve` library as I outlined in the first code box. Make a second function that will load the dictionary, call it `load_dict`, it will use the second code box snippet to load the dictionary. You can then let the user choose which function to run. – KIO Jun 03 '20 at 22:16
  • i added a new answer because i couldn't write the code here, can you please solve the problem i mentioned – Omar Khaled Jun 04 '20 at 14:46
1
import shelve
words = {}
def save_dict(words):
    s = shelve.open('shelve2.db', writeback=True)
    s['Dict'] = words
    s.sync()
    s.close()


def load_dict():
    s = shelve.open('shelve2.db', writeback=True)
    dict = s['Dict']
    print(dict)
    s.close()


ask = input('Do you want to add a new word?(y/n): ')
if ask == 'y':
    new_word = input('what is the new word?: ')
    word_meaning = input('what does the word mean?: ')
    words[new_word] = word_meaning
    save_dict(words)
elif ask == 'n':
    load_dict()

so this is my code after making the save_dict and load_dict functions, it works fine but when i run the program and write a new_word and word_meaning it overwrites the previous data, i believe i am missing something in the save_dict function, if you can point the problem to me i would be so grateful

  • 1
    Good job so far. Your mistake is easy to understand. Say you run the program for the first time and add 10 words. The 10-word dictionary gets saved. Next time you run the program you immediately decide to add 5 words. The 5-word dictionary gets saved and overwrites your previous dictionary... Solution? Load the words dictionary before you make additions to it. Also, in your `load_dict()` you should return the `dict` that you load and store it in `words`, as in, that way you will actually load and use the dictionary you saved before. – KIO Jun 04 '20 at 15:08
  • i understood your point but i couldn't apply it, if you can tell me what code should i write and where, that will actually help me a lot, because i will understand better if i could see the program running correctly, i tried so many times, but this shelve library is driving me crazy, i am having problems to understand it, thank you and i am sorry if i am wasting your time. – Omar Khaled Jun 05 '20 at 06:43
  • 1
    I updated my answer with an adapted version of your code. – KIO Jun 05 '20 at 10:03
  • thank you so much, i tried it and it finally worked – Omar Khaled Jun 05 '20 at 14:46