Reputation: 145
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?
Upvotes: 1
Views: 7900
Reputation: 1124558
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)
Upvotes: 1
Reputation: 16940
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'}
>>>
Upvotes: 1