Python dictionary in to html table

后端 未结 7 1291
刺人心
刺人心 2020-12-23 21:33

Is there any way to print the python dictionary in to a table in HTML. I have a python dictionary and am sending to HTML by using

return render_template(\'i         


        
7条回答
  •  臣服心动
    2020-12-23 22:21

    so I wanted an easy way to generate html from python dictionary with only inline styles (because emails) and couldn't find anything that I was satasfied with so I wrote this,

    it's very simple to use and easy to add styles to

    col1 col2 col3 col4
    value11 value21 value31 value41
    value12 value22 value32 value42
    value13 value23 value33 value43

    lets say you have the following dictionary

    myDict = {
        'col1' : ['value11', 'value12', 'value13'],
        'col2' : ['value21', 'value22', 'value23'],
        'col3' : ['value31', 'value32', 'value33'],
        'col4' : ['value41', 'value42', 'value43'],
    }
    

    it can be converted with

    class HTML:
    
        def __init__(self, Header, tableStyles = {}, trStyles = {}, thStyles = {}):
            self.tableStyles = HTML._styleConverter(tableStyles)
            trStyles = HTML._styleConverter(trStyles)
            thStyles = HTML._styleConverter(thStyles)
            self.rows = []
            self.Header= f''
            for th in Header:
                self.Header += f'\n{th}'
            self.Header += '\n'
    
        @staticmethod
        def _styleConverter(styleDict : dict):
            if styleDict == {}:
                return ''
            styles = ''
            for [style, value] in styleDict.items():
                styles +=f'{style}: {value};'
            return f'style="{styles}"'
    
        def addRow(self, row, trStyles = {}, tdStyles = {}):
            trStyles = HTML._styleConverter(trStyles)
            tdStyles = HTML._styleConverter(tdStyles)
            temp_row = f'\n'
            for td in row:
                temp_row += f'\n{td}'
            temp_row += '\n'
            self.rows.append(temp_row)
    
    
        def __str__(self):
    
    
            return \
    f'''
    
    {self.Header}
    {''.join(self.rows)}
    
    ''' def dictionaryToHTMLTable(dict : dict): html = HTML(Header = dict.keys(), tableStyles={'margin': '3px'}, trStyles={'background-color': '#7cc3a97d'}, thStyles={ 'color': 'white'}) for i, row in enumerate(zip(*dict.values())): print(row) if i%2 == 0: BGC = 'aliceblue' else: BGC = '#c2d4e4' html.addRow(row, trStyles={'background-color' : BGC}, tdStyles={'padding': '1rem'}) return html

    and to output

    print(dictionaryToHTMLTable(myDict))
    
    

提交回复
热议问题