Python代码将字典转换为JSON文件
这段代码将一个字典转化为JSON格式并写入一个名为'class_indices.json'的文件中。
首先,代码通过train_dataset.class_to_idx获取一个字典,该字典将花的类别映射到一个数字。
然后,代码通过dict((val, key) for key, val in flower_list.items())将字典中的键值对交换,即将数字作为键,将花的类别作为值,得到一个新的字典cla_dict。
接下来,代码使用json.dumps(cla_dict, indent=4)将cla_dict转化为JSON格式的字符串,并使用缩进格式化输出(indent=4)。
最后,代码通过打开一个名为'class_indices.json'的文件,并将JSON字符串写入文件中。
# {'daisy': 0, 'dandelion': 1, 'roses': 2, 'sunflower': 3, 'tulips': 4}
flower_list = train_dataset.class_to_idx
cla_dict = dict((val, key) for key, val in flower_list.items())
# write dict into json file
json_str = json.dumps(cla_dict, indent=4)
with open('class_indices.json', 'w') as json_file:
json_file.write(json_str)
原文地址: https://www.cveoy.top/t/topic/i3uV 著作权归作者所有。请勿转载和采集!