如何在字典中添加键值对以在python中以JSON格式转储数据?

时间:2014-01-31 12:55:51

标签: python json

我想将键值对添加到具有一些键值对的现有数组中,然后以JSON格式转储此信息。

我尝试了以下代码:

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)

但是这段代码在行"student_data['result'] = 'pass'

中给出了错误

我尝试从[]

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

但是只有键才能在文件中打印而没有值。

我该如何纠正?

2 个答案:

答案 0 :(得分:0)

你有一个包含字典的列表。使用索引:

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

或者在编写时添加以后的列表

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

# ...

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

注意:当您应该测试相等性时,不要对整数使用身份测试。仅仅因为CPython 发生实习生小整数,不会使is 1成为一个好主意。请改用== 1

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)

在上面的示例中,我使用conditional expressions来设置resultschool键;您也可以直接在字典文字中使用它们:

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)

答案 1 :(得分:0)

如果您将student_data更改为字典,那么您可以尝试这样的更新字典。您将从student_data中删除[],因此它将更改为dict对象。

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

或者你可以分配它:

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