Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带颜色格式的excel嵌套字典_Python_Excel_Colors - Fatal编程技术网

Python 带颜色格式的excel嵌套字典

Python 带颜色格式的excel嵌套字典,python,excel,colors,Python,Excel,Colors,我的字典是这样的: dict1 = { '2020-10-11' : { 'group1':{ 1 : 2356, 21 : 10001, 34 : 234

我的字典是这样的:

dict1 = { '2020-10-11' : { 
                           'group1':{ 
                                     1 : 2356,
                                     21 : 10001,
                                     34 :  234 
                                   },
                            'group2':{
                                     11 : 999,
                                     2  : 101,
                                     13 : 1234 
                                     } 
                         },
         '2020-10-12' : { 
                           'group1':{ 
                                     11 : 236,
                                     21 : 100,
                                     34 :  34 
                                   },
                            'group2':{
                                     1 : 99,
                                     3 : 121,
                                     2 : 12 
                                     } 
                         }


}
我希望我的输出像这样:

要求是:每个日期的颜色都应该不同。 我用这种方法尝试过:

reform = {(level1_key, level2_key, level3_key): values
          for level1_key, level2_dict in dict1.items()
          for level2_key, level3_dict in level2_dict.items()
          for level3_key, values      in level3_dict.items()}

out = pd.DataFrame(reform,index = ['amount']).T
names=['date', 'group', 'id']
out.index.set_names(names, inplace=True)
在xls中输出:


在此之后,如何使用python在excel中进行颜色格式化?第一步是完全展平结构,以便嵌套值的二维表示形式:

dict1 = {'2020-10-11': {'group1': {1: 2356, 21: 10001, 34: 234}, 'group2': {11: 999, 2: 101, 13: 1234}}, '2020-10-12': {'group1': {11: 236, 21: 100, 34: 34}, 'group2': {1: 99, 3: 121, 2: 12}}}
def flatten(d, c = []):
   flag = True
   for a, b in d.items():
     if isinstance(b, dict):
        yield from flatten(b, c=c+[a] if flag or not c else [*c[:-2],'',a])
     else:
        yield c+[a, b] if flag or not c else [*(['']*(len(c))),a, b]
     flag = False

data = list(flatten(dict1))
#[['2020-10-11', 'group1', 1, 2356], ['', '', 21, 10001], ['', '', 34, 234], ['', 'group2', 11, 999], ['', '', 2, 101], ['', '', 13, 1234], ['2020-10-12', 'group1', 11, 236], ['', '', 21, 100], ['', '', 34, 34], ['', 'group2', 1, 99], ['', '', 3, 121], ['', '', 2, 12]]
接下来,根据结果创建一个
pd.DataFrame
,并应用颜色:

import pandas as pd
df = pd.DataFrame(data, columns=['Date', 'Group', 'ID', 'Amount'])
writer = pd.ExcelWriter('test_rsults12.xls', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
c_pool = iter([workbook.add_format({'bg_color': '#fff0c1'}), workbook.add_format({'bg_color': '#d5e6f5'})])
fmt = None
for i in range(len(data)):
   if data[i][0]:
      fmt = next(c_pool)
   worksheet.set_row(i+1, cell_format=fmt)

writer.save()
结果: