2017-02-23 82 views
0

我對Python非常陌生,我試圖將我的字典的內容稱爲python_diction(位於較大的文件中),並將該數據保存到名爲python_diction_saved.json的新文件中。我覺得我很接近我目前收到的錯誤是python_diction_saved.json未定義。將字典保存到文件

任何幫助將不勝感激。

import json 
f = open("python_diction.txt","w") 
python_diction = {} 
python_diction["items"] = [] 
python_diction["items"].append({"hello":1,"hi":2}) 
python_diction["items"].append({"hello":42,"hi":65}) 
python_diction["numbers"] = [1,2,3,5,7,8] 
f.write(json.dumps(python_diction_saved.json)) 
f.close() 
+0

'python_diction_saved' =>'python_diction' –

+0

大,這解決了第一個回溯錯誤,但現在我得到另一個回溯錯誤...... f.write(json.dumps(python_diction_saved.json)) AttributeError:'dict'對象沒有屬性'json' – AvSmith

+0

:'python_diction_saved.json' =>'python_diction' –

回答

1

爲了寫你python_diction一個名爲python_diction_saved.json文件,你可以使用json.dump(以避免必須自己編寫):

import json 
python_diction = {} 
python_diction["items"] = [] 
python_diction["items"].append({"hello":1,"hi":2}) 
python_diction["items"].append({"hello":42,"hi":65}) 
python_diction["numbers"] = [1,2,3,5,7,8] 

with open("python_diction_saved.json") as output_file: 
    json.dump(python_diction, output_file)