繁体   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