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

时间:2016-11-12 14:51:10

标签: python dictionary updating shelve

我有一个搁置的词典' 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'}

1 个答案:

答案 0 :(得分:0)

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

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

此代码将dict加载到内存中,称为update方法,将update方法的结果分配回工具架,然后删除更新的内存中字典。但dict.update返回None,你完全覆盖了字典。您将dict放入变量,更新,然后保存变量。

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}