简体   繁体   中英

python : HTML table creation from dictionary items

I am not much aware of HTML. I want to create a HTML table from my dictionary items. Below is my code and output. I want 'th html tag' key of dictionary should be on left side and 'td html tag' value of key on right.

Output from my code

from testdatabase import DBhelper

db=DBhelper()

item=db.get_user("KASHIF IQBAL")
print(item)

dict1={'ID':item['id'],
'NAME':item['NAME'],
'Project':item['PROJECT_ID'],
'SUBDATE':item['SUBMIT_DATE'],
'ERM Month':item['ERM_MONTH'],
'ERM_SUBMIT':item['ERM_SUBMIT'],
'Claim Period':item['CLAIM_PERIOD'],
'SITE Location':item['LOCATION'],
'Trip Type':item['TRIP_TYPE'],
'Expense Info':item['EXPENSE_INFO'],
'Market claim AmtINR':item['MARKET_CLAIM_INR'],
'Concur Claim AmtINR':item['CONCUR_CLAIM_INR'],
'Market claim AmtEUR':item['MARKET_CLAIM_EUR'],
'Concur claim AmtEUR':item['CONCUR_CLAIM_EUR']
}

f1=open("expense_test.html",'w')
html = """<html><table border="1">"""
for  data in dict1:
   html+="<tr><th>"+data+"</th></tr>".format(data)
   html += r"<tr><td>"+str(dict1[data])+"</td></tr>"
html += "</table></html>"
f1.write(''.join(html))
print(html)

change your for loop to:

for data in dict1:
   html += "<tr>"
   html += "<td>"+data+"</td>"
   html += "<td>"+str(dict1[data])+"</td>"
   html += "</tr>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM