Python實(shí)現(xiàn)將字典內(nèi)容寫(xiě)入json文件
Python中有序字典和無(wú)序字典,一鍵多值字典。
Python將字典內(nèi)容寫(xiě)入json文件。
1、無(wú)序字典
目前了解三種,在Python中直接默認(rèn)的是無(wú)序字典,這種不會(huì)按照你插入的順序排序,即使你對(duì)字典排序后,返回的也是一個(gè)list變量,而不是字典,倘若你將這個(gè)list字典后,又會(huì)變回?zé)o序字典。
例子如下:
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來(lái)初始化字典。
例子如下:
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、寫(xiě)入json
字典內(nèi)容寫(xiě)入json時(shí),需要用json.dumps將字典轉(zhuǎn)換為字符串,然后再寫(xiě)入。
json也支持格式,通過(guò)參數(shù)indent可以設(shè)置縮進(jìn),如果不設(shè)置的話,則保存下來(lái)會(huì)是一行。
例子:
4.1 無(wú)縮進(jìn)
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 有縮進(jìn)
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)

方法補(bǔ)充
下面是參考上文代碼整理出的另一種實(shí)現(xiàn)方法,可以參考一下
"""
將整個(gè)數(shù)據(jù)集分為train和test,相應(yīng)的也分別分配整個(gè)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目標(biāo)文件
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]) # 測(cè)試集圖片的路徑
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實(shí)現(xiàn)將字典內(nèi)容寫(xiě)入json文件的詳細(xì)內(nèi)容,更多關(guān)于Python字典寫(xiě)入json的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
將Python代碼打包成可調(diào)用SDK的四種方法小結(jié)(適用于移動(dòng)端 App)
Python是一門(mén)功能強(qiáng)大、生態(tài)豐富的語(yǔ)言,廣泛用于數(shù)據(jù)處理、機(jī)器學(xué)習(xí)和后端服務(wù),然而,Python并不是原生的移動(dòng)端開(kāi)發(fā)語(yǔ)言,如果希望在移動(dòng)端App中調(diào)用Python代碼,最好的方式是將Python代碼打包成SDK,所以本文給大家介紹了幾種Python代碼打包成可調(diào)用SDK的方法2025-04-04
python中datetime模塊中strftime/strptime函數(shù)的使用
這篇文章主要介紹了python中datetime模塊中strftime/strptime函數(shù)的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
python 讀取yaml文件的兩種方法(在unittest中使用)
這篇文章主要介紹了python 讀取yaml文件的兩種方法(在unittest中使用),幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-12-12
Python scipy的二維圖像卷積運(yùn)算與圖像模糊處理操作示例
這篇文章主要介紹了Python scipy的二維圖像卷積運(yùn)算與圖像模糊處理操作,涉及Python數(shù)學(xué)運(yùn)算與圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
python通過(guò)微信發(fā)送郵件實(shí)現(xiàn)電腦關(guān)機(jī)
這篇文章主要為大家詳細(xì)介紹了python通過(guò)微信發(fā)送郵件實(shí)現(xiàn)電腦關(guān)機(jī),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
舉例詳解Python中循環(huán)語(yǔ)句的嵌套使用
這篇文章主要介紹了舉例詳解Python中循環(huán)語(yǔ)句的嵌套使用,是Python入門(mén)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-05-05
如何實(shí)現(xiàn)更換Jupyter Notebook內(nèi)核Python版本
這篇文章主要介紹了如何實(shí)現(xiàn)更換Jupyter Notebook內(nèi)核Python版本,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
解讀torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度
這篇文章主要介紹了torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
pandas如何將表中的字符串轉(zhuǎn)成數(shù)值型
在用pd.read_csv讀數(shù)據(jù)時(shí),將要轉(zhuǎn)換數(shù)據(jù)類型的列名和類型名構(gòu)成字典,傳給dtype,怎么轉(zhuǎn)換呢,下面小編給大家分享下pandas將表中的字符串轉(zhuǎn)成數(shù)值型,感興趣的朋友一起看看吧2023-02-02
python字符串與url編碼的轉(zhuǎn)換實(shí)例
今天小編就為大家分享一篇python字符串與url編碼的轉(zhuǎn)換實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05

