2016-11-12 7 views
1

私はファイル内に孤立した辞書 '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']) 

ご協力いただきありがとうございます。 UPDATE これはインポートされ、私は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'} 
+0

あなたは 'shelf ['word_dictionary']'の中に何を入れているのですか?あなたは、2番目のスニペットでそれ自体の価値として棚を設定しているようです。 – amirouche

+1

どちらのスニペットも、shelvedリストのあるファイルとは異なる.pyファイルから取得し、そのファイルにインポートします。それは辞書を漬けているファイルで である: word_dictionary = {「ホープ単語」:「hope_words」、「メリー単語」:「merry_words」、「驚嘆単語」:「amazement_words」} 私がword_dictionary設定私はコードの残りの部分で毎回シェルフを参照する必要はありません。棚を使っているのは初めてのことなので、これが必要でないなら私に修正してください! – Jess

答えて

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 

UPDATE

棚が閉じているときに、新しいデータが保存されているかどうか質問がありました。ここに例があります

# 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} 
+0

ありがとうございます - 頭痛の数時間をほっとしました!私はちょうど約絶望のハハにボトルに行っただろう。 – Jess

+0

この方法は本当に良いですが、ファイルを閉じてもう一度開くと永久に保存するようには見えませんか? – Jess

+0

@Jess私は 'close'を生き延びたアップデートの例を追加しました。問題がある場合は、コードにバグがある可能性があります。 – tdelaney

関連する問題