字典保存但覆盖最后输入的密钥

时间:2015-08-18 04:13:50

标签: python dictionary

我很难尝试根据输入保存和更新字典到pickle文件。运行命令并输入新节目后,字典永远不会添加新的键和值。这是为什么?我已经跟踪了很多帖子一个月了,并尝试了如何做到这一点的基本方法,但它总是被覆盖。

import pickle

user_settings = {'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {}}}
user_input = input('Command: ')

def changedict():
    if user_input == 'run':
        newshow = input("New show: ")
        user_notify = user_settings['mjp3LhFUUS8ZM7zW8UV4tHTDyD4=']['notify']
        print(user_notify)
        user_notify[newshow] = 242525
        pickle.dump(user_settings, open("save.p", "wb"))
        print(user_settings)
    elif user_input == 'read':
        readdict = pickle.load(open("save.p", "rb"))
        print(readdict)

    else:
        print('Not a command')

changedict()

当我运行并添加新节目时,我会收到{'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {'test': 242525}}},但在再次播放并尝试添加新节目后,我会收到{'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {'test2': 242525}}}。我想要的是让字典像{'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {'test': 242525}, {'test2': 242525}}}

一样保存

1 个答案:

答案 0 :(得分:2)

我猜你说当你再次运行程序时,你的意思是你使用 - python <script.py>再次完全运行脚本。

然后问题是,对于程序的每次运行,您将用户设置字典重新定义为 -

user_settings = {'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {}}}

如果用户输入命令run,那么您只是将用户的输入添加到此user_settings,您不会再次从该文件中读取字典。

因此,这将覆盖用户输入的内容。

您可能只想在无法从文件中读取时才设置。

示例 -

import pickle

try:
    user_settings = pickle.load(open("save.p", "rb"))
except (IOError, pickle.UnpicklingError):
    user_settings = {'mjp3LhFUUS8ZM7zW8UV4tHTDyD4=': {'notify': {}}}

IOError - 如果文件 - save.p不存在,它将捕获异常。 pickle.UnpicklingError - 如果文件 - save.p - 不包含正确的pickle数据,它会捕获异常。