【工程实践】将字典保存为json文件

1.问题描述

        工作中在将标签数据送入模型之前,需要写出映射关系并建立字典完成由字符到id的转换,在算法工程化时,需要用到此映射字典。

2.保存方法        

2-1 pickle

import pickle
#写入文件
with open('data.json', 'wb') as fp:
    pickle.dump(my_dict, fp)

#读取文件
with open('data.json', 'rb') as fp:
    data = pickle.load(fp)

2-2 json

import json
# 写入文件
with open("pkg_name_index.json", "w") as outfile:
    #ensure_ascii=False 显示中文
    json.dump(pkg_name_index, outfile,ensure_ascii=False)

# 读取文件
with open('pkg_name_index.json', encoding='utf-8') as reader:
    result = json.load(reader)

猜你喜欢

转载自blog.csdn.net/weixin_44750512/article/details/130521715
今日推荐