简体   繁体   中英

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

I'm very new to python and I'm still trying to learn dictionaries. I made a dictionary of lists but I'm trying to append a value that I added to an existing list within the dictionary. However when I try to append that new value to that list, it doesn't write to the JSON file, it just keeps the file as it is.

I have this code

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()

(Ignore the print statements, they were just for when I was trying to debug)

Currently my JSON file looks like this with only one student and his class

 {"student1": ["math"]}

I eventually want my dictionary to look like this

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

How do I append new values to an existing list and how do I add new keys with its corresponding lists?

In your code, you are updating the local variable but not writing the updates to the file. What you need is to dump the final dictionary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM