首页 > 解决方案 > 我如何在字典中保留/保存用户输入?

问题描述

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)

如您所见,我想制作一本字典,但我不知道如何保存用户的输入。我想获取用户输入并将其保存在字典中,因此下次他使用该程序时,他可以看到他之前添加的所有内容

标签: python-3.x

解决方案


当您在正在运行的 Python 程序中创建和填充(填充)字典时,该字典仅在程序运行时存在。当您关闭程序时-该内存被擦除并且所做的任何修改都不会被存储。

正如 Tomerikoo 指出的那样,这个解决方案:搁置词典将允许您在程序关闭后保留您的词典。我从链接中复制代码(jabaldonedo 的解决方案)并为您注释它以清楚起见。

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.

当您关闭和打开程序时,字典不会自动弹出到您的运行内存中——您需要编写代码来访问它。它可以作为游戏菜单中的一个选项,例如“加载现有的单词词典”。

回到 jabaldonedo 的解决方案:

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.

编辑:这是在您的答案中提供的特定上下文中如何使用它的方法。请注意,我导入了一个附加库并更改了shelve访问命令中的标志。

正如我在评论中提到的,在将新内容写入字典之前,您应该首先尝试加载字典:

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.")



推荐阅读