在python中,如何循环字典但保留对其进行的更改

时间:2010-12-20 00:33:25

标签: python-3.x

所以基本上我是python和编程的新手。我想知道你有一个情况,你有一个字典,并询问用户是否要添加或删除字典中的术语。所以我知道如何添加或删除字典中的术语,但如何在下次程序启动时“保存”该数据。基本上,如果用户在字典中添加了一个单词然后我问他们是否想要使用while循环返回主菜单,那么你将如何制作它以使他们添加的单词现在永久地在字典中返回到菜单并启动程序?

这就是我所拥有的。请注意,我是初学者,所以如果它看起来很奇怪,那么对不起......大声笑......没什么大不了的:

loop=None
while True:
    #The initial dictionary
    things={"house":"a place where you live",
            "computer":"you use to do lots of stuff",
            "iPod":"mp3 player",
            "TV":"watch shows on it",
            "bed":"where you sleep",
            "wii":"a game system",
            "pizza":"food"}


    #Menu
    print("""

        Welcome to the Dictionary of Things
            Choose your preference:

        0-Quit
        1-Look up a Term
        2-Add a Term
        3-Redefine a Term
        4-Delete a Term

        """)

    choice=input("\nWhat do you want to do?: ")

elif choice=="2": #Adds a term for the user
        term=input("What term do you want to add? ")
        if term not in things:
            definition=input("Whats the definition? ")
            things[term]=definition #adds the term to the dictionary
            print(term,"has been added to the dictionary")
            menu=input("""
                    Would you like to go back to the menu?
                            Yes(Y) or No(N):  """)
                if menu=="Y":
                    loop=None  ----->#Ok so if they want to go back to the menu the program should remember what they added
                elif menu=="N":
                    break

3 个答案:

答案 0 :(得分:1)

正如Misha已经说过的那样,pickle是一个好主意,但更简单的方法是使用shelve模块,它在内部使用(c)pickle并完全按照你的要求行事。 来自文档:

import shelve

d = shelve.open(filename) # open

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)

答案 1 :(得分:1)

更新

您的问题是您在每个循环开始时重新定义字典。将字典的开始定义移动到While循环之前,您就可以开始工作了。


字典和列表是可变对象。因此,如果它在函数中被修改,它在被调用的地方保持修改:

def main_function():
    do someting
    mydict = {'a': 2, 'b': 3}
    subfunction(mydict)
    print mydict

def otherfunction(thedict):
    dict['c'] = 5

如果您现在运行main_function,它将打印出包含'c'的字典。

答案 2 :(得分:0)

我认为可能有助于更具体地说明程序的结构。听起来您希望将字典保存为外部文件,以便在应用程序的后续运行时加载/重新加载。在这种情况下,您可以像这样使用pickle库:

import pickle
dictionary = {"foo": "bar", "spam": "egg"}

# save it to a file...
with open("myfile.dct", "wb") as outf:
    pickle.dump(dictionary, outf)

# load it in again:
reloaded = {}
with open("myfile.dct", "rb") as inf:
    reloaded = pickle.load(inf)