Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tabulate Dictionary containing two values per key

I am using the Tabulate 0.7.7 package to tabulate a dictionary with two values per key.

I have this code.

from tabulate import tabulate

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

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

I want the following table to be produced -

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

However, the code is the following table -

Name    Age
------  ----------------
Dave    ('13', 'Male')
Sarah   ('16', 'Female')

How can I solve this problem?

like image 699
vik1245 Avatar asked Nov 29 '25 11:11

vik1245


2 Answers

If you flatten the dictionary items, from (k, (v1, v2)) to (k, v1, v2), you can get the correct format:

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
like image 172
Psidom Avatar answered Dec 02 '25 02:12

Psidom


I'm not sure that it is possible given the structure of your input data d.

Reformatting your data as such (see below) will give the desired result.

d = {'Name': ['Dave', 'Sarah'], 'Age': [13, 16], 'Gender': ['Male', 'Female']

like image 20
undefinederrorname Avatar answered Dec 02 '25 02:12

undefinederrorname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!