更新写在文件上的搁置词典

Updating A Shelved Dictionary written on a file

我在一个文件中有一个搁置的字典'word_dictionary',我可以在主程序中访问它。我需要让用户能够向字典中添加条目。但是我无法将条目保存在搁置的字典中,并且出现错误:

Traceback (most recent call last):
  File "/Users/Jess/Documents/Python/Coursework/Coursework.py", line 16, in <module>
    word_dictionary= dict(shelf['word_dictionary'])
TypeError: 'NoneType' object is not iterable

当代码循环返回时 - 代码在第一个 运行 上工作。

这是更新字典的代码:

    shelf = shelve.open("word_list.dat")
    shelf[(new_txt_file)] = new_text_list
    shelf['word_dictionary'] = (shelf['word_dictionary']).update({(new_dictionary_name):(new_dictionary_name)})
    #not updating
    shelf.sync()
    shelf.close()

这是更新未完成后不起作用的代码(我不认为这是问题的一部分,但我可能是错的)

shelf = shelve.open("word_list.dat")
shelf.sync()
word_dictionary= dict(shelf['word_dictionary'])

提前感谢您的帮助和耐心等待! 更新 这是我调用 word_dictionary 的代码的开头:

while True:
 shelf = shelve.open("word_list.dat")
 print('{}'.format(shelf['word_dictionary']))
 word_dictionary= dict(shelf['word_dictionary'])
 print(word_dictionary)
 word_keys = list(word_dictionary.keys())
 shelf.close()

这是我要添加到的原始词典的位置:

shelf['word_dictionary'] = {'Hope Words': 'hope_words', 'Merry Words': 'merry_words', 'Amazement Words': 'amazement_words'}

问题是您必须将搁置数据库更新与数据库加载到内存中的对象分开。

shelf['word_dictionary'] = (shelf['word_dictionary']).update({(new_dictionary_name):(new_dictionary_name)})

这段代码将 dict 加载到内存中,调用它的 update 方法,将 update 方法的结果分配回书架,然后删除更新的内存中字典。但是 dict.update returns None 你完全覆盖了字典。你把字典放在一个变量中,更新,然后保存变量。

words = shelf['word_dictionary']
words.update({(new_dictionary_name):(new_dictionary_name)})
shelf['word_dictionary'] = words

更新

有一个问题是关闭架子时是否保存新数据。这是一个例子

# Create a shelf with foo
>>> import shelve
>>> shelf = shelve.open('word_list.dat')
>>> shelf['foo'] = {'bar':1}
>>> shelf.close()

# Open the shelf and its still there
>>> shelf = shelve.open('word_list.dat')
>>> shelf['foo']
{'bar': 1}

# Add baz
>>> data = shelf['foo']
>>> data['baz'] = 2
>>> shelf['foo'] = data
>>> shelf.close()

# Its still there
>>> shelf = shelve.open('word_list.dat')
>>> shelf['foo']
{'baz': 2, 'bar': 1}