简体   繁体   中英

How to add a key-value pair in dictionary for dumping data in JSON format in python?

I want to add a key-value pair to an already existing array having some key-value pairs, and then dump this information in JSON format.

I tried following code:

import json

student_data = [{'stu_name':'name','id no':7}]

if result is 1:    
    student_data['result'] = 'pass'
else:
    student_data['result'] = 'fail'

if school is 1:
   student_data['school'] = 'secondary school'
else:
   student_data['school'] = 'primary school'

with open(file.json, "w") as f:
    json.dump(student_data, f)

But this code gives me error in line "student_data['result'] = 'pass'

I tried removing [] from student_data = [{'stu_name':'name','id no':7}]

but then only keys get printed in the file without values.

How can I correct this?

You have a list with a dictionary. Either use indexing:

student_data[0]['result'] = 'pass'

or add the list later , when writing:

student_data = {'stu_name':'name','id no':7}

# ...

with open(file.json, "w") as f:
    json.dump([student_data], f)

Note: Do not use identity tests for integers when you should be testing for equality instead. Just because CPython happens to intern small integers, doesn't make using is 1 a good idea. Use == 1 instead:

student_data = {'stu_name':'name','id no':7}

student_data['result'] = 'pass' if result == 1 else 'fail'
student_data['school'] = 'secondary school' if school == 1 else 'primary school'

with open(file.json, "w") as f:
    json.dump([student_data], f)

In the above example I used conditional expressions to set the result and school keys; you can use those directly in the dictionary literal too:

student_data = [{'stu_name': 'name', 'id no':7,
                 'result': 'pass' if result == 1 else 'fail',
                 'school': 'secondary school' if school == 1 else 'primary school',
                }]

with open(file.json, "w") as f:
    json.dump(student_data, f)

If you are changing student_data as dictionary then you can try something like this to update the dictionary. You are remove [] from student_data so, it will change to dict object.

>>> student_data = {'stu_name':'name','id no':7}
>>> student_data.update({'result':'pass'})
>>> student_data
{'stu_name': 'name', 'id no': 7, 'result': 'pass'}
>>>

Or You can just assign it:

>>> student_data = {'stu_name':'name','id no':7}
>>> student_data['result'] = 'pass'
>>> student_data
{'stu_name': 'name', 'id no': 7, 'result': 'pass'}
>>>

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