如何转换包含嵌套列表的嵌套字典

时间:2021-05-21 18:28:08

标签: python-3.x list csv dictionary nested

我有一个包含(嵌套列表)的嵌套字典。我已经浏览了 Stackoverflow 中的几篇文章(hereherehere)。但是,我不知道如何解决这些问题。字典看起来像

{ 'LinReg': { 'First': [ array([ 0.83333333, -0.77777778, -0.6       ,  0.72222222]),
                         array([0.4       , 0.05555556, 0.4       , 0.44444444])],
              'Second': [ array([[5.16666667, 3.28571429, 2.4       , 6.38461538]]),
                              array([[ 4.83333333, 23.        ,  1.26666667,  3.22222222]])],
              'Third': [ array([[ 5.16666667, -3.28571429, -2.4       ,  6.38461538]]),
                                     array([[ 4.83333333, 23.        ,  1.26666667,  3.22222222]])],
              'Fourth': [ array([0.83333333, 0.77777778, 0.6       , 0.72222222]),
                                array([0.4       , 0.05555556, 0.4       , 0.44444444])]},
  'kNN': { 'First': [ array([ 0.        , -0.75      ,  0.5       ,  0.41666667]),
                      array([ 0.        , -0.8       , -0.1       ,  0.08333333])],
           'Second': [ array([[1.        , 2.33333333, 4.        , 7.4       ]]),
                           array([[       inf, 2.75      , 1.4       , 1.41666667]])],
           'Third': [ array([[ 0.        , -2.33333333,  4.        ,  7.4       ]]),
                                  array([[ 1.        , -2.75      , -1.4       ,  1.41666667]])],
           'Fourth': [ array([0.        , 0.75      , 0.5       , 0.41666667]),
                             array([0.        , 0.8       , 0.1       , 0.08333333])]}}

我正在尝试的代码

a = ["Album/Track"] + dictionary.keys()
x = list(set([y for z in dictionary.values() for y in z.keys()]))
rows = [a] + [[q] + [dictionary[p].get(q, "-") for p in a[1:]] for q in x]
with open("my.csv", "wb") as csvfile:
    writer = csv.writer(csvfile)
    for row in rows:
        writer.write(row)

如何将这本字典转换成如下所示的 CSV 文件?

LinReg First Array1_Output1, Array1_Output2, and so on
             Array2_Output1, Array2_Output2, and so on
       Second 
       Third
       Fourth
kNN First Array1_Output1, Array1_Output2, and so on
             Array2_Output1, Array2_Output2, and so on
       Second 
       Third
       Fourth

1 个答案:

答案 0 :(得分:0)

如果 d 是你的问题字典,你可以这样做:

import csv

with open("data.csv", "w") as f_in:
    writer = csv.writer(f_in)
    for k, v in d.items():
        for kk, vv in v.items():
            for vvv in vv:
                writer.writerow([k, kk] + list(vvv.ravel()))

创建 data.csv(来自 LibreOffice 的屏幕截图):

enter image description here