题目中漏掉了一些数据,根据处理结果要求构建了一下,主要对字典健值的操作,使用tabulate库打印出格式化表格,参考如下代码:
from tabulate import tabulate
orig = {'portfolio': {
'date': '2013-11-27',
'cash': 1,
'ABC': 5,
'DEF': 8
},'Val/Unit*':{
'cash': 10000,
'ABC': 686.50,
'DEF': 504.11
}
}
t=list(orig.keys())[0]
vol=orig[t]
table_header = ['Capital type', 'Volume', 'Val/Unit*', 'Value in ¥*']
date=vol['date']
print(f'Your {t} on {date}:')
vs=dict()
for a,b,c in zip(list(vol.keys())[1:],list(orig[t].values())[1:],orig['Val/Unit*'].values()):
vs.update({a:b*c})
orig.update({"Value in ¥*": vs})
table_data=[(x,y,z,u) for x,y ,z ,u in zip(['Cash','Shares of ABC','Shares of DEF'],list(orig[t].values())[1:],list(orig['Val/Unit*'].values()),list(orig['Value in ¥*'].values()))]
#print(table_data)
print(tabulate(table_data, headers=table_header, tablefmt='grid'))
print(f'TOTAL VALUE{sum(orig["Value in ¥*"].values()):>45}')
运行结果:
F:\2021\qa\ot3>t1
Your portfolio on 2013-11-27:
+----------------+----------+-------------+---------------+
| Capital type | Volume | Val/Unit* | Value in ¥* |
+================+==========+=============+===============+
| Cash | 1 | 10000 | 10000 |
+----------------+----------+-------------+---------------+
| Shares of ABC | 5 | 686.5 | 3432.5 |
+----------------+----------+-------------+---------------+
| Shares of DEF | 8 | 504.11 | 4032.88 |
+----------------+----------+-------------+---------------+
TOTAL VALUE 17465.38
如对你有帮助 ,请点采纳按钮支持一下。