首頁 > 軟體

Python實現將字典內容寫入json檔案

2022-08-19 22:02:08

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:Users9lingDesktopYiLiuWuDatasettrainyuedongguan_select"
total_json_path = r"C:Users9lingDesktopYiLiuWuDatasettrainyuedongguan.json"
test_path = r"C:Users9lingDesktopYiLiuWuDatasettesthas_yiliuwuyuedongguan_test"
test_json_path = r"C:Users9lingDesktopYiLiuWuDatasettesthas_yiliuwuyuedongguan_testyuedongguan_test.json"
train_path = r"C:Users9lingDesktopYiLiuWuDatasettrainyuedongguan"
train_json_path = r"C:Users9lingDesktopYiLiuWuDatasettrainyuedongguanyuedongguan.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的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com