简体   繁体   中英

Python Tabulate doesn't produce the correct table from dictionary

I am using Tabulate version 0.7.7 for Python 3.6

This is my code so far for a simple test using a dictionary.

from tabulate import tabulate

d = {"Dave":"13", "Bob":"15"}

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

The result I want is

Name    Age
------  -----
Dave    13
Bob     15

But what I am getting is

Name    Age
------  -----
1       1
3       5

Can someone help me please?

One question - Can I fix this using tabulate or should I be using a different python package?

You can access items attribute of dict. Like this. It'll give you result you want.

>>> print(tabulate(d.items(), headers = headers))
Name      Age
------  -----
Bob        15
Dave       13

You need to give tabulate a list of tuples. One way to do this with a dictionary is to use unpack the items like so:

from tabulate import tabulate

d = {"Dave":"13", "Bob":"15"}

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

which returns

Name      Age
------  -----
Dave       13
Bob        15

Alternatively, you can use different lists and zip them together. Tabulate is looking for inputs that look like this:

names = ['Dave','Bob']
ages = ['13','15']

d = zip(names,ages)

print(d)

which returns:

[('Dave', '13'), ('Bob', '15')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM