全球视点!Python实现将字典内容写入json文件
目录
1、无序字典2、有序字典3、一键多值字典4、写入json4.1 无缩进4.2 有缩进方法补充Python中有序字典和无序字典,一键多值字典。
Python将字典内容写入json文件。
1、无序字典
目前了解三种,在Python中直接默认的是无序字典,这种不会按照你插入的顺序排序,即使你对字典排序后,返回的也是一个list变量,而不是字典,倘若你将这个list字典后,又会变回无序字典。
【资料图】
例子如下:
import operator x = {"label": "haha", "data": 234, "score": 0.3} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) print x print type(x) print sorted_x print type(sorted_x) print dict(sorted_x)
2、有序字典
如果我们想保持字典按照我们插入的顺序有序怎么办?可以用OrderedDict来初始化字典。
例子如下:
from collections import OrderedDict x = OrderedDict() x["label"] = "haha" x["data"] = 234 x["score"] = 0.3 print x print type(x)
3、一键多值字典
如果我们想用一键多值字典怎么办,可以使用defaultdict,例子如下:
from collections import defaultdict video = defaultdict(list) video["label"].append("haha") video["data"].append(234) video["score"].append(0.3) video["label"].append("xixi") video["data"].append(123) video["score"].append(0.7) print video print type(video)
4、写入json
字典内容写入json时,需要用json.dumps将字典转换为字符串,然后再写入。
json也支持格式,通过参数indent可以设置缩进,如果不设置的话,则保存下来会是一行。
例子:
4.1 无缩进
from collections import defaultdict, OrderedDict import json video = defaultdict(list) video["label"].append("haha") video["data"].append(234) video["score"].append(0.3) video["label"].append("xixi") video["data"].append(123) video["score"].append(0.7) test_dict = { "version": "1.0", "results": video, "explain": { "used": True, "details": "this is for josn test", } } json_str = json.dumps(test_dict) with open("test_data.json", "w") as json_file: json_file.write(json_str)
4.2 有缩进
from collections import defaultdict, OrderedDict import json video = defaultdict(list) video["label"].append("haha") video["data"].append(234) video["score"].append(0.3) video["label"].append("xixi") video["data"].append(123) video["score"].append(0.7) test_dict = { "version": "1.0", "results": video, "explain": { "used": True, "details": "this is for josn test", } } json_str = json.dumps(test_dict, indent=4) with open("test_data.json", "w") as json_file: json_file.write(json_str)
方法补充
下面是参考上文代码整理出的另一种实现方法,可以参考一下
""" 将整个数据集分为train和test,相应的也分别分配整个json文件 """ import os import random import json total_select_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\train\yuedongguan_select" total_json_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\train\yuedongguan.json" test_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\test\has_yiliuwu\yuedongguan_test" test_json_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\test\has_yiliuwu\yuedongguan_test\yuedongguan_test.json" train_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\train\yuedongguan" train_json_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset\train\yuedongguan\yuedongguan.json" data = json.load(open(total_json_path))["labels"] # test_data = json.load(open(test_json_path))["labels"] all_select_path = os.listdir(total_select_path) all_file_path = [] # 待分配的图片路径 for item in all_select_path: file_path = os.path.join(total_select_path, item) all_file_path.append(file_path) # print(all_file_path) idx = [i for i in range(len(all_select_path))] random.shuffle(idx) # 在idx上改变 def copy_dir(src_path, target_path): # src_path原文件,target_path目标文件 if os.path.isdir(src_path) and os.path.isdir(target_path): filelist_src = os.listdir(src_path) for file in filelist_src: path = os.path.join(os.path.abspath(src_path), file) if os.path.isdir(path): path1 = os.path.join(os.path.abspath(target_path), file) if not os.path.exists(path1): os.mkdir(path1) copy_dir(path, path1) else: with open(path, "rb") as read_stream: contents = read_stream.read() path1 = os.path.join(target_path, file) with open(path1, "wb") as write_stream: write_stream.write(contents) return True else: return False test_data_dir = {"labels": []} for item in idx[:41]: with open(all_file_path[item], "rb") as read_stream: contents = read_stream.read() path1 = os.path.join(test_path, all_file_path[item].split("\\")[-1]) # 测试集图片的路径 with open(path1, "wb") as write_stream: write_stream.write(contents) for s in data: if s["filename"].split("\\")[-1] == all_file_path[item].split("\\")[-1]: test_data_dir["labels"].append(s) # print(s) json_test_str = json.dumps(test_data_dir, indent=4) with open(test_json_path, "w") as json_file: json_file.write(json_test_str) print(test_data_dir) print(len(test_data_dir["labels"])) print("*"*30) train_data_dir = {"labels": []} for item in idx[41:]: with open(all_file_path[item], "rb") as read_stream: contents = read_stream.read() path2 = os.path.join(train_path, all_file_path[item].split("\\")[-1]) with open(path2, "wb") as write_stream: write_stream.write(contents) for s1 in data: if s1["filename"].split("\\")[-1] == all_file_path[item].split("\\")[-1]: train_data_dir["labels"].append(s1) json_train_str = json.dumps(train_data_dir, indent=4) with open(train_json_path, "w") as json_file: json_file.write(json_train_str) print(train_data_dir) print(len(train_data_dir["labels"])) # print(s)
以上就是Python实现将字典内容写入json文件的详细内容,更多关于Python字典写入json的资料请关注脚本之家其它相关文章!
X 关闭
X 关闭
- 1亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 2现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 3如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 4AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 5转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 6充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 7好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 8名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?
- 9亚马逊云科技成立量子网络中心致力解决量子计算领域的挑战
- 10京东绿色建材线上平台上线 新增用户70%来自下沉市场