如何将多重字典写入csv文件? [蟒蛇]

时间:2019-04-12 10:03:38

标签: python-3.x

我有一个像这样的字典

     list2=[  {'char1': ['ABC',  'DEF',  'GHI',  'JKL',  'MNO','PQO','RST']},
              {'fact': ['1111', '2222', '3333', '4444']},         
              {'range1' : [ 'A123 ',  'B456',  ' C579']},

              {'char2': ['Hai',  'What',  'where',  'when ',  'who',  'has',  'had' ] },

              {'fact1' : ['11', '22', '33', '44']}]

我有以下代码:

  import csv
  with open('my_file.csv', mode='w') as f:
      csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
      csv_writer.writerow([list(i.keys()) for i in list1])
      csv_writer.writerow([list(i.values()) for i in list1])

我想将结果放入数据框

当前结果以水平格式存储,我需要以垂直格式存储。

我正在尝试将其导出为CSV并让表格如下所示:

所需的输出

      char1    fact    range1  char2    fact
      ABC      1111    A123    Hai      11
      DEF      2222    B456    What     22
      GHI      3333    C579    where    33
      JKL      4444            when     44
      MNO                      who
      PQO                      has
      RST                      had

1 个答案:

答案 0 :(得分:2)

尝试

# data
list2 = [
 {'char1': ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQO', 'RST']},
 {'fact': ['1111', '2222', '3333', '4444']},
 {'range1': ['A123 ', 'B456', ' C579']},
 {'char2': ['Hai', 'What', 'where', 'when ', 'who', 'has', 'had']},
 {'fact1': ['11', '22', '33', '44']}
]

# create a dataframe for each list
dfs = [pd.DataFrame(key_value) for key_value in list2]

# concatenate those dataframes along axis 1
df = pd.concat(dfs, axis=1)

df的结果

  char1  fact range1  char2 fact1
0   ABC  1111  A123     Hai    11
1   DEF  2222   B456   What    22
2   GHI  3333   C579  where    33
3   JKL  4444    NaN  when     44
4   MNO   NaN    NaN    who   NaN
5   PQO   NaN    NaN    has   NaN
6   RST   NaN    NaN    had   NaN

保存到csv

df.to_csv('filename.csv', index=False)