python:从字典项创建HTML表

时间:2018-04-21 04:52:27

标签: python html dictionary

我不太了解HTML。我想从我的字典项创建一个HTML表。以下是我的代码和输出。我想要' html标记'字典的键应该在左侧并且&#t; html标签'右边的钥匙价值。

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)

1 个答案:

答案 0 :(得分:0)

将您的for循环更改为:

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