【问题标题】:Splitting a nested dictionary into several dicts将嵌套字典拆分为多个字典
【发布时间】:2021-12-09 05:34:58
【问题描述】:

我想按语言将以下嵌套字典拆分为不同的字典为每种语言创建一个新的 JSON 文件/字典。

之后我想将它们重新合并在一起。

感谢任何关于如何继续的建议!

示例:

{
  "All": {
    "label_es_ES": "Todo",
    "label_it_IT": "Tutto",
    "label_en_EN": "All", 
    "label_fr_FR": "Tout"
  },
  "Searchprofile": {
    "label_es_ES": "Perfil de búsqueda",
    "label_it_IT": "Profilo di ricerca",
    "label_en_EN": "Search profile", 
    "label_fr_FR": "Profil de recherche"
  },

到目前为止我得到了什么:

import json

store_file = open( 'test.txt' , "w" )

with open('translations.json') as json_file:
   data = json.load(json_file)
       for label, translations in data.items():
           for key in translations:
               if key==('label_en_EN'):
                   json.dump(???, store_file)
            .....'''

【问题讨论】:

  • 您能否详细说明您希望如何格式化各个 JSON 文件?根据您提供的输入判断,为每种语言创建一个新的 JSON 文件只是一个键值对。 IE。 "label_es_ES": "Perfil de búsqueda"
  • 感谢您的快速回复!!单个字典的格式应保持不变,但只包含一种语言:{ "All": { "label_es_ES": "Todo", }, "Searchprofile": { "label_es_ES": "Perfil de búsqueda", },

标签: python json dictionary split nested


【解决方案1】:

循环浏览你的字典:

from pprint import pprint

data = {
  "All": {
    "label_es_ES": "Todo",
    "label_it_IT": "Tutto",
    "label_en_EN": "All", 
    "label_fr_FR": "Tout"
  },
  "Searchprofile": {
    "label_es_ES": "Perfil de búsqueda",
    "label_it_IT": "Profilo di ricerca",
    "label_en_EN": "Search profile", 
    "label_fr_FR": "Profil de recherche"
  }
}
new_data = dict()
for word,transl_dict in data.items():
    for lbl, transl in transl_dict.items():
        if not(lbl in new_data.keys()):
            new_data[lbl] = dict()
        new_data[lbl][word] = transl

pprint(new_data)

输出:

{'label_en_EN': {'All': 'All', 'Searchprofile': 'Search profile'},
 'label_es_ES': {'All': 'Todo', 'Searchprofile': 'Perfil de búsqueda'},
 'label_fr_FR': {'All': 'Tout', 'Searchprofile': 'Profil de recherche'},
 'label_it_IT': {'All': 'Tutto', 'Searchprofile': 'Profilo di ricerca'}}

您当然可以将 label_... 字典单独转储到文件中。

编辑:如果您已经知道有哪些标签,则输出原始预期字典会更短:

labels = ["label_es_ES", "label_it_IT", "label_en_EN", "label_fr_FR"]
for label in labels:
    label_dict = {x: {label: data[x][label]} for x in data}
    pprint(label_dict)
    # or dump directly to files;
    with open(f"{label}.json", "w", encoding="utf-8") as f:
        json.dump(label_dict, f, indent=4, ensure_ascii=False)

Json 文件以 utf-8 格式编写,因此您可以在 json 中看到特殊字符。以后打开文件时别忘了指定编码(utf-8)!

【讨论】:

  • 我刚刚阅读了您的评论,看来这不是您想要的。但这不是更有意义吗?它避免了 label_... 作为键的重复
  • 好的,看看我更新的答案!
  • 它应该已经将文件转储到label_<en_EN>.json(我在一分钟后添加了转储部分,所以您可能会错过它)。你能指定是什么字符导致问题吗?
  • 我编辑了我的答案,因此 json 现在写为 utf-8。现在应该可以毫无问题地读取特殊字符
  • 看看this。加载字典后,update 应该很简单。如果您在这样做时遇到困难,请打开一个新问题
【解决方案2】:
from itertools import islice

def chunks(data, SIZE=10000):
    it = iter(data)
    for i in range(0, len(data), SIZE):
        yield {k:data[k] for k in islice(it, SIZE)}
        
for item in chunks({i:i for i in range(10)}, 3):
    print item
    

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2021-09-09
  • 2014-05-17
  • 2011-05-04
  • 2018-10-04
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多