簡體   English   中英

如何將新值附加到字典中的列表並將其寫入 JSON 文件

[英]How to append a new value to a list in a dictionary and write it to JSON file

我對 python 很陌生,我仍在努力學習字典。 我制作了一個列表字典,但我試圖附加一個我添加到字典中現有列表的值。 但是,當我嘗試將該新值附加到該列表時,它不會寫入 JSON 文件,它只是保持文件原樣。

我有這個代碼

with open('students.json') as j:
    students = json.load(j)
for i in students:
    #print "entered here4"
    if(name == i):
            print "entered here5"
            for k in students[i]:
                print "entered here6"
                print k
                if(classes == k):
                    print "classes exists Success"
                     sys.exit()
                else:
                        students[i].append(classes)
                                #x = students[i].append(classes) 
                                #with open ('students.json', 'w') as f:
                                    #json.dump(x,f)
                                #this didn't work for me, it wrote "null" to my JSON file
                                print "user added"
                                sys.exit()

(忽略打印語句,它們只是在我嘗試調試時使用)

目前我的 JSON 文件看起來像這樣,只有一個學生和他的班級

 {"student1": ["math"]}

我最終希望我的字典看起來像這樣

{'student1': ["math", "biology"], "student2": ["chemistry"], "student3": ["History", "biology", "physics"]}

如何將新值附加到現有列表以及如何添加新鍵及其對應列表?

在您的代碼中,您正在更新局部變量,但未將更新寫入文件。 你需要的是轉儲最終的字典。

with open("students.json", "w") as jsonFile:
    json.dump(students, jsonFile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM