python - 从字典中将指定的键值加载到 json 对象中

标签 python json dictionary parsing

我希望将字典加载到 json 对象中,但不是所有键和值。

示例字典:

full_dict = {
            'code': 1,
            'length': 20,
            'height': 45,
            'name':"book"
        }

我想把它做成json对象,我用过

json.dumps(full_dict)

但我只想上传该词典中选定的字段,因为仅在这些字段中:

part_dict = {
            'length':20,
            'height':45,
            'name':"book"
        }

总结起来,我希望使用:

json.dumps(full_dict)

并期待以下 json 对象:

{"length": 20, "height": 45, "name": "book"}

谢谢,感谢您的宝贵时间。

最佳答案

您可以在将字典写入磁盘之前对其进行过滤:

full_dict = {
            'code': 1,
            'length': 20,
            'height': 45,
            'name':"book"
        }

keep = ['length', 'height', 'name']

partial_dict = {k: v for k, v in full_dict.items() if k in keep}
print(partial_dict)

如果有很多字段,将 keep 变成字典以进行 O(1) 查找是一个简单的优化。

关于python - 从字典中将指定的键值加载到 json 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807816/

相关文章:

python - 日期时间索引 : what is the purpose of 'freq' attribute?

python 将 beautifulsoup 输出转换为 dict/json

android - 如何使用 Retrofit 2.0 (Kotlin) 正确解析嵌套的 JSON 对象?

android - 为每个 fragment 更改 QueryUtils 中的值

python - 为什么 TF-IDF 计算需要这么长时间?

javascript - 模块没有在 Electron 的渲染过程中导入

python - 按查询集中的对象排除

c# - 在 C# 中将对象视为属性字典

swift - 使用 swift 字典返回它的所有值?

python - 为什么我的 pygame 窗口在关闭之前只保持打开一秒钟?