gpt4 book ai didi

python - 将嵌套字典拆分为多个字典

转载 作者:行者123 更新时间:2023-12-05 03:36:15 25 4
gpt4 key购买 nike

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

最佳答案

循环遍历字典:

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

关于python - 将嵌套字典拆分为多个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69679155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com