将嵌套字典拆分为多个字典。

3
我想把以下嵌套字典按语言分成不同的字典,并为每种语言创建一个新的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)
            .....'''

1
你能详细说明一下你希望如何格式化每个JSON文件吗?根据你提供的输入,为每种语言创建一个新的JSON文件只需要一个键值对。例如:"label_es_ES": "Perfil de búsqueda"。 - Kyle Dixon
谢谢您的快速回复!!单个字典的格式应保持不变,但只包含一种语言:{ "All": { "label_es_ES": "全部", }, "Searchprofile": { "label_es_ES": "搜索配置文件", }, } - heroldonkey
2个回答

2

使用循环遍历字典:

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)!


1
我刚刚看了你的评论,似乎不完全符合你的要求。但这样做更有意义,不是吗?它避免了将label_...作为键重复使用。 - Tranbi
我应该澄清一下,在这种情况下,重复是需要的。每个json文件、.txt文件或其他文件,都应该包含一个单一的语言和格式{ "All": { "label_es_ES": "Todo", }, "Searchprofile": { "label_es_ES": "Perfil de búsqueda", } 等等非常感谢,我正在查看您的提案,也许我可以适应它。 - heroldonkey
1
它应该已经转储了文件到 label_<en_EN>.json(我在一分钟后添加了转储部分,所以你可能错过了)。你能指明哪个字符引起了问题吗? - Tranbi
1
我编辑了我的答案,以便将json现在写成utf-8。特殊字符现在应该可以无问题地读取了。 - Tranbi
1
看一下这个。一旦你加载了字典,使用update应该很简单。如果你有困难,请开一个新的问题。 - Tranbi
显示剩余4条评论

1
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
    

1
您的回答可以通过提供更多支持信息来改善。请进行[编辑]以添加进一步细节,例如引用或文档,以便他人可以确认您的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接