脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现将字典内容写入json文件

Python实现将字典内容写入json文件

2022-08-20 09:30夏洛的网 Python

这篇文章主要为大家详细介绍了如何利用Python语言实现将字典内容写入json文件,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下

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)

Python实现将字典内容写入json文件

 

2、有序字典

如果我们想保持字典按照我们插入的顺序有序怎么办?可以用OrderedDict来初始化字典。

例子如下:

from collections import OrderedDict

x = OrderedDict()

x["label"] = "haha"
x["data"] = 234
x["score"] = 0.3

print x
print type(x)

Python实现将字典内容写入json文件

 

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)

Python实现将字典内容写入json文件

 

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)

Python实现将字典内容写入json文件

 

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)

Python实现将字典内容写入json文件

 

方法补充

下面是参考上文代码整理出的另一种实现方法,可以参考一下

"""
将整个数据集分为train和test,相应的也分别分配整个json文件
"""
import os
import random
import json

total_select_path = r"C:Users9lingDesktopYiLiuWuDataset	rainyuedongguan_select"
total_json_path = r"C:Users9lingDesktopYiLiuWuDataset	rainyuedongguan.json"
test_path = r"C:Users9lingDesktopYiLiuWuDataset	esthas_yiliuwuyuedongguan_test"
test_json_path = r"C:Users9lingDesktopYiLiuWuDataset	esthas_yiliuwuyuedongguan_testyuedongguan_test.json"
train_path = r"C:Users9lingDesktopYiLiuWuDataset	rainyuedongguan"
train_json_path = r"C:Users9lingDesktopYiLiuWuDataset	rainyuedongguanyuedongguan.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的资料请关注服务器之家其它相关文章!

原文地址:https://blog.csdn.net/liuxiao214/article/details/80115924

延伸 · 阅读

精彩推荐
  • PythonPython导入txt数据到mysql的方法

    Python导入txt数据到mysql的方法

    这篇文章主要介绍了Python导入txt数据到mysql的方法,涉及Python操作txt文件及mysql数据库的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    huaweitman7762020-06-02
  • Pythonpython Selenium实现付费音乐批量下载的实现方法

    python Selenium实现付费音乐批量下载的实现方法

    这篇文章主要介绍了python Selenium实现付费音乐批量下载的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,...

    1treeS8482021-05-21
  • PythonPython实现的tab文件操作类分享

    Python实现的tab文件操作类分享

    这篇文章主要介绍了Python实现的tab文件操作类分享,本文直接给出实现代码,需要的朋友可以参考下 ...

    脚本之家3632020-05-14
  • PythonPython正则捕获操作示例

    Python正则捕获操作示例

    这篇文章主要介绍了Python正则捕获操作,结合具体实例形式分析了Python基于正则表达式的分组、捕获、替换等相关操作技巧,需要的朋友可以参考下...

    罗兵3652020-12-03
  • PythonPython实现希尔排序算法的原理与用法实例分析

    Python实现希尔排序算法的原理与用法实例分析

    这篇文章主要介绍了Python实现希尔排序算法,简单讲述了希尔排序的原理并结合具体实例形式分析了Python希尔排序的具体实现方法与使用技巧,需要的朋友可...

    Alex Yu1652020-12-09
  • Python深入解析Python中的lambda表达式的用法

    深入解析Python中的lambda表达式的用法

    这篇文章主要介绍了深入解析Python中的lambda表达式的用法,包括其与def之间的区别,需要的朋友可以参考下...

    阿托5872020-07-30
  • Pythonpython处理变量交换与字符串及判断的小妙招

    python处理变量交换与字符串及判断的小妙招

    本文记录一些 Python 日常编程中的小妙招,并使用 IPython 进行交互测试,让我们更好的了解和学习 Python 的一些特性,对大家的学习或工作具有一定的价值,...

    忆想不到的晖11132022-01-17
  • Pythonflask中的wtforms使用方法

    flask中的wtforms使用方法

    这篇文章主要介绍了flask中的wtforms使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    海燕。9962021-03-19