如何使用 python 将列从 CSV 文件转换为 json,以便键和值对来自 CSV 的不同列?

How to convert columns from CSV file to json such that key and value pair are from different columns of the CSV using python?

我有一个 CSV 文件,其中包含标签及其不同语言的翻译:

name                      en_GB     de_DE
-----------------------------------------------
ElementsButtonAbort       Abort     Abbrechen
ElementsButtonConfirm     Confirm   Bestätigen
ElementsButtonDelete      Delete    Löschen
ElementsButtonEdit        Edit      Ãndern

我想使用 Python 将此 CSV 转换为 JSON 为以下模式:

{
    "de_De": {
        "translations":{
            "ElementsButtonAbort": "Abbrechen"
                       }
             },
   "en_GB":{
       "translations":{
           "ElementsButtonAbort": "Abort"
                      }
             }
 }

如何使用 Python 执行此操作?

说你的数据是这样的:

import pandas as pd

df = pd.DataFrame([["ElementsButtonAbort", "Abort", "Arbrechen"],
                   ["ElementsButtonConfirm", "Confirm", "Bestätigen"],
                   ["ElementsButtonDelete", "Delete", "Löschen"],
                   ["ElementsButtonEdit", "Edit", "Ãndern"]],
                   columns=["name", "en_GB", "de_DE"])

那么,这可能不是最好的方法,但至少它有效:

df.set_index("name", drop=True, inplace=True)
translations = df.to_dict()

现在,如果您想准确地获得显示为所需输出的字典,您可以执行以下操作:

for language in translations.keys():
    _ = translations[language]
    translations[language] = {}
    translations[language]["translations"] = _

最后,如果您希望将字典保存到 JSON:

import json

with open('PATH/TO/YOUR/DIRECTORY/translations.json', 'w') as fp:
    json.dump(translations, fp)