【发布时间】: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