簡體   English   中英

將包含多個嵌套字典的字典轉換為 a.csv

[英]Converting a dict containing multiple nestet dicts into a .csv

我在 Python 中有一個包含多個嵌套字典的字典,我想將它們寫入 csv 文件。

字典看起來像這樣:

dict = {'case1':{'variant1':{'Name':['1','2','3'],'Values':[1,2,3],'Unit':['one','two','three']}},
                 'variant2':{'Name':['1','2','3'],'Values':[1,2,3],'Unit':['one','two','three']},
        'case2':{'variant1':{'Name':['1','2','3'],'Values':[1,2,3],'Unit':['one','two','three']}},
                 'variant2':{'Name':['1','2','3'],'Values':[1,2,3],'Unit':['one','two','three']}}

因此,具有不同變體的多個案例,每個變體包含三個對應名稱、值和單位的列表。 如前所述,我想將此 dict 轉換為 csv 文件,理想情況下,不同情況下的變體很容易區分。 由於 csv 將主要在 Excel 中使用,我將舉例說明我想象它在 Excel 中的外觀。 理想是這樣的: test_dict2csv

我知道如何將單個變體(因此一組名稱、值和單位)寫入 csv,其代碼如下所示:

keys = sorted(dict['case1']['variant1'].keys())
with open("test_output.csv", "w") as outfile:
   writer = csv.writer(outfile,delimiter=';')
   writer.writerow(keys)
   writer.writerows(zip(*[dict['case1']['variant1'][key] for key in keys]))

但我不知道如何在同一行向下添加下一個變體和案例。

如果有人有想法,我將不勝感激:)

如果要為每個元素生成一條記錄,每個列表中生成一個元素,可以先展平字典,然后像這樣編寫:

import csv
from pprint import pprint

dict_data = {
    "c1": {
        "v1": {
            "Name": ["s111", "s112", "s113"],
            "Values": [111, 112, 113],
            "Unit": ["11one", "11two", "11three"],
        },
        "v2": {
            "Name": ["s121", "s122", "s123"],
            "Values": [121, 122, 123],
            "Unit": ["12one", "12two", "12three"],
        },
    },
    "c2": {
        "v1": {
            "Name": ["s211", "s212", "s213"],
            "Values": [211, 212, 213],
            "Unit": ["21one", "21two", "21three"],
        },
        "v2": {
            "Name": ["s221", "s222", "s223"],
            "Values": [221, 222, 223],
            "Unit": ["22one", "22two", "22three"],
        },
    },
}


def flatten_dict(curr_dict, curr_key=""):
    new_dict = {}
    for new_key, value in curr_dict.items():

        if curr_key == "":
            combined_key = new_key
        else:
            combined_key = curr_key + "_" + new_key

        if isinstance(value, dict):
            new_dict.update(flatten_dict(value, combined_key))
        else:
            new_dict[combined_key] = value

    return new_dict


flat = flatten_dict(dict_data)
pprint(flat)


keys = sorted(flat.keys())
with open("test_output_all.csv", "w") as outfile:
    writer = csv.writer(outfile, delimiter=";")
    writer.writerow(keys)
    writer.writerows(zip(*[flat[key] for key in keys]))

(我只是將 dict 更改為更清楚哪個值是哪個,並且鍵名更短,結構與您的相似)。 這打印:

{'c1_v1_Name': ['s111', 's112', 's113'],
 'c1_v1_Unit': ['11one', '11two', '11three'],
 'c1_v1_Values': [111, 112, 113],
 'c1_v2_Name': ['s121', 's122', 's123'],
 'c1_v2_Unit': ['12one', '12two', '12three'],
 'c1_v2_Values': [121, 122, 123],
 'c2_v1_Name': ['s211', 's212', 's213'],
 'c2_v1_Unit': ['21one', '21two', '21three'],
 'c2_v1_Values': [211, 212, 213],
 'c2_v2_Name': ['s221', 's222', 's223'],
 'c2_v2_Unit': ['22one', '22two', '22three'],
 'c2_v2_Values': [221, 222, 223]}

在文件中:

c1_v1_Name;c1_v1_Unit;c1_v1_Values;c1_v2_Name;c1_v2_Unit;c1_v2_Values;c2_v1_Name;c2_v1_Unit;c2_v1_Values;c2_v2_Name;c2_v2_Unit;c2_v2_Values
s111;11one;111;s121;12one;121;s211;21one;211;s221;22one;221
s112;11two;112;s122;12two;122;s212;21two;212;s222;22two;222
s113;11three;113;s123;12three;123;s213;21three;213;s223;22three;223

如果您絕對需要 header 就像您圖片中的那個,那么 header 行的一些預處理應該是可行的,以便在單獨的行上打印每個嵌套級別。

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM