字典读写训练

Posted exesoft

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典读写训练相关的知识,希望对你有一定的参考价值。

字典写入json文件中:

import json
stu_mark={}
stu_mark["Name"]=input("Name=")
stu_mark["English"]=float(input("English="))
stu_mark["Music"]=float(input("Music="))
stu_mark["Chinese"]=float(input("Chinese="))
print(stu_mark)
# with open("stu_mark.json", mode=‘w‘, encoding=‘utf-8‘) as fp:
#     json.dump(stu_mark, fp,ensure_ascii=False,indent=2)
f=open("stu_mark.json",w,encoding=utf-8)
json.dump(stu_mark,f,False,2)
f.close()

从json文件读入到字典中:

import json

# with open("stu_mark.json", mode=‘r‘, encoding=‘utf-8‘) as fp:
#     print(json.load(fp))
f=open("stu_mark.json",r,encoding=utf-8)
stu_mark=json.load(f)
print(type(stu_mark))
print(stu_mark)
f.close()

 

以上是关于字典读写训练的主要内容,如果未能解决你的问题,请参考以下文章

Python snippet(代码片段)

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

关于字典编辑及文件读写

Python基础之字典元祖常用字符串方法文件读写