![](/img/trans.png)
[英]How to format python dictionary print output like JavaScript?
[英]Python 3, format print output of a dictionary in several column (like a formated table)
我想像表格一樣格式化我的打印 output。 這是我的代碼:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
result = b'[{"id":"865776","name":"US 2019","url":"www.abc.com"},
{"id":"646829496481089588","name":"MultiDomainDemo","url":"www.n149.mydomain.com
/o/rw48vavc/manage/organization/overview"},{"id":"549236","name":"Developer
Sandbox","url":"www.overview"},
{"id":"566327653141842188","name":"NetAssoc","url":"www.n6/organization"}]'
response_list = eval(result.decode())
print("id name")
print("_________________________")
for n in response_list:
print (n['id'], " " ,n['name'])
結果是這樣的:
id name
_________________________
865776 US 2019
646829496481089588 MultiDomainDemo
549236 Developer Sandbox
566327653141842188 NetAssoc
但我想要這樣:
id name
_________________________
865776 US 2019
646829496481089588 MultiDomainDemo
549236 Developer Sandbox
566327653141842188 NetAssoc
您可以使用tabulate
模塊。 您還可以使用tablefmt
參數更改表格樣式。
from tabulate import tabulate
result = b'[{"id":"865776","name":"US 2019","url":"www.abc.com"}, {"id":"646829496481089588","name":"MultiDomainDemo","url":"www.n149.mydomain.com/o/rw48vavc/manage/organization/overview"},{"id":"549236","name":"Developer Sandbox","url":"www.overview"}, {"id":"566327653141842188","name":"NetAssoc","url":"www.n6/organization"}]'
response_list = eval(result.decode())
header = response_list[0].keys()
rows = [x.values() for x in response_list]
print(tabulate(rows, headers=header, tablefmt='grid'))
Output:
+--------------------+-------------------+---------------------------------------------------------------+
| id | name | url |
+====================+===================+===============================================================+
| 865776 | US 2019 | www.abc.com |
+--------------------+-------------------+---------------------------------------------------------------+
| 646829496481089588 | MultiDomainDemo | www.n149.mydomain.com/o/rw48vavc/manage/organization/overview |
+--------------------+-------------------+---------------------------------------------------------------+
| 549236 | Developer Sandbox | www.overview |
+--------------------+-------------------+---------------------------------------------------------------+
| 566327653141842188 | NetAssoc | www.n6/organization |
+--------------------+-------------------+---------------------------------------------------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.