我正在使用 Tabulate 0.7.7 包将每个键有两个值的字典制成表格。

我有这个代码。

from tabulate import tabulate

d = {"Dave":("13", "Male") , "Sarah":("16", "Female")}

headers = ["Name", "Age", "Gender"]
print(tabulate(d.items(), headers = headers))

我希望生成下表 -
Name    Age    Gender
------  -----  ---------
Dave    13     Male
Sarah   16     Female

但是,代码如下表-
Name    Age
------  ----------------
Dave    ('13', 'Male')
Sarah   ('16', 'Female')

我怎么解决这个问题?

最佳答案

如果将字典项展平,从 (k, (v1, v2)) 到 (k, v1, v2),您可以获得正确的格式:

from tabulate import tabulate   ​
d = {"Dave":("13", "Male") , "Sarah":("16", "Female")}
​
headers = ["Name", "Age", "Gender"]
print(tabulate([(k,) + v for k,v in d.items()], headers = headers))

Name      Age  Gender
------  -----  --------
Sarah      16  Female
Dave       13  Male

关于每个键包含两个值的 Python 制表字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42235918/

10-12 19:26