PYTHON将字典打印成表格

毕设项目助手 其他问答 1
{portfolio = { 
    'date' : '2013-11-27',
    'cash' : 10000,
    'ABC' : 5,
    'DEF' : 8
}}
Your portfolio on 2013-11-27:
Capital type          | Volume  | Val/Unit*    | Value in ¥*
------------------------+-----------+---------------+------------------
 Cash                    |      1       |10000.00   |    10000.00
 Shares of ABC     |      5       |    686.50   |     3432.50
 Shares of DEF     |      8       |    504.11   |     4032.87
------------------------+-----------+--------------+---------------------
 TOTAL VALUE                                           17465.37

回复

共2条回复 我来回复
  • 源码货栈
    这个人很懒,什么都没有留下~
    评论
    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}')
    
    0条评论
  • 毕设工坊
    这个人很懒,什么都没有留下~
    评论
    portfolio = [{
        'date' : '2013-11-27',
        'cash' : 10000,
        'ABC' : 5,
        'DEF' : 8
    },{
        'date' : '2013-11-28',
        'cash' : 10001,
        'ABC' : 7,
        'DEF' : 5
    }]
    for k in portfolio[0].keys():
        print(f'{k:>11}',end="")
    print()
    for d in portfolio:
        for v in d.values():
            print(f'{v:>11}',end="")
        print()
    
    0条评论

发表回复

登录后才能评论