2013-11-09 24 views
0

我很努力地將字典寫入/附加到文本文件。使用'a'我的字典的形式爲{'word_one:'definition_one'} {'word_two:'definition_two'} ...而不是我認爲我會得到的(並且想要){'word_one:'definition_one','word_two:' definition_two'...}。我在做錯什麼。對不起,這樣一個基本的問題。我想,我明白詞典和書面文本文件,但是...... 的代碼是:使用追加的Python返回多個字典

import ast 
import operator 

def collectDict(): 

    # first initialize your final_dict and dante_dict dictionary 
    final_dict={} 
    with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic: 
      dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary 


    (dante_dict,final_dict) = define_words(dante_dict,final_dict) # call the define_words function to update your dictionaries 


    # write your dictionaries 

    with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile: 
      outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term 

    with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'a', encoding = 'utf-8') as finalfile: 
      finalfile.write(str(final_dict)) 
    with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'r', encoding = 'utf-8') as finalfile: 
      prelim_dict = ast.literal_eval(finalfile.read()) 
      print(prelim_dict) 


def define_words(dante_dict,final_dict): 
    # your already written function without the initialization (first 3 lines) and file writing part 
    print('There were ', len(dante_dict), ' entries before defining this word') 
    key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0] 
    print('The next word to define is ', key_to_find) # show which word needs defining 

    definition = input('Definition ? : ') # prompt for definition 
    final_dict = {} 

    if key_to_find in dante_dict: 
     final_dict.append[key_to_find] = definition 
     del dante_dict[key_to_find] # remove entry from source dictionary once new definition is done 
    print('the end length is : ' ,len(dante_dict)) # check that entry has been removed from source 

    return(dante_dict,final_dict) # you return the dictionaries for the other function 

,我開始與文本文件是:

{'amico ': 1, "'Segnor": 1, 'volgere': 1, 'spaventate,': 1, "s'avvantaggia": 1, 'livore': 1, 'disposta ': 1, 'pennelli': 1, 'atto': 15, 'Berti': 1, 'atti': 7, 'Gaia ': 1, 'alzato,': 1, 'reda': 2, "d'ossa": 1, 'rede': 1, 'solvesi': 1, 'Dopo': 3, 'amico,': 1, 'Sardi,': 1, 'pastore,': 2, 'sana ': 1,…} 
+0

[pickle](http://docs.python.org/2/library/pickle.html)是此任務的工具。 –

回答

1

final_dict是字典的列表 ,而不是一本字典。通過使用list.append(),您不斷向該列表添加新的字典。

使它成爲一個字典來代替,然後分配給對字典鍵:

final_dict = {} 

if key_to_find in dante_dict: 
    final_dict[key_to_find] = definition 
    del dante_dict[key_to_find] 

注意,存在循環在整個dante_dict鍵,看看是否的關鍵是它沒有一點時,你可以使用key in dict,這是一種更快的方法。最後的del dict[key]表達式替換代碼中的dante_dict.pop()表達式。

+0

謝謝你對我如此耐心。我現在得到的dict對象沒有方法追加。我應該使用更新還是我又做了什麼錯誤? – user1478335

+0

@ user1478335:糟糕,不,這是我的一個複製粘貼錯誤。 '.append'在這裏不需要。 –