【问题标题】:Updating A Shelved Dictionary written on a file更新写在文件上的搁置字典
【发布时间】:2016-11-12 14:51:09
【问题描述】:

我在一个文件中有一个搁置的字典“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'] 里面放了什么?您似乎在第二个 sn-p 中将架子设置为自身的值。
  • 两个 sn-ps 来自不同的 .py 文件,而不是带有搁置列表的文件,然后我将其导入该文件。在它被腌制的文件中,字典是: word_dictionary = {'Hope Words': 'hope_words', 'Merry Words': 'merry_words', 'Amazement Words': 'amazement_words'} 我将 word_dictionary 自身设置为 I don'在其余代码中,每次都必须参考书架。这是我第一次使用架子,如果没有必要,请纠正我!

标签: python dictionary updating shelve


【解决方案1】:

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

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}

【讨论】:

  • 非常感谢 - 您缓解了几个小时的头痛!我只是绝望地去瓶子哈哈。
  • 这个方法确实不错——但是如果我关闭文件再打开它似乎并不能永久保存?
  • @Jess 我添加了一个在close 中幸存的更新示例。如果您遇到问题,则可能是您的代码中的错误。
  • 该列表在shelf.close() 中仍然存在,但是如果我在用户重新打开模块并运行它时输入新值后关闭模块,那么用户所做的添加就消失了
  • @Jess “关闭模块”是指退出程序并再次执行它。它应该可以很好地生存。也许您的代码中有一个地方可以覆盖它或删除文件或其他东西。您可以发布一个简短的可运行示例来演示该问题吗?这是解决问题的最佳方法。
猜你喜欢
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多