如何使用字典中的值在 Python 中创建 Table
How to create a Table in Python using values from a Dictionary
我正在使用 Python 并且我有一个包含多个列表的字典,每个列表中正好有 5 个元素。
我想做的是打印一个漂亮的 table,其中仅包含字典中列表中的元素,没有任何键。问题是因为列表中每个元素的长度不同,它打印出一个非常难看的 table.
在此先感谢您的帮助,
嗨,我假设你想要这样的东西:
{
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
打印为:
512 2 20
512 2 20
512 2 20
512 2 20
512 2 20
您可以使用 pandas 模块来执行此操作:
import pandas as pd
a={
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
b = pd.DataFrame(a) # create a dataframe from dictionary
b.columns = ['' for _ in range(len(b.columns))] # replace column names(keys) with empty string
print(b.to_string(index=False)) # print dataframe as table but hide row indices
编辑:
要将键打印为行,您可以使用转置函数,如下所示:
import pandas as pd
a={
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
b = pd.DataFrame(a) # create a dataframe from dictionary
b = b.T # get transpose of b and save to b
b.columns = ['' for _ in range(len(b.columns))] # replace column names(keys) with empty string
print(b.to_string(index=False)) # print dataframe as table but hide row indices
输出应该是:
512 512 512 512 512
2 2 2 2 2
20 20 20 20 20
我正在使用 Python 并且我有一个包含多个列表的字典,每个列表中正好有 5 个元素。
我想做的是打印一个漂亮的 table,其中仅包含字典中列表中的元素,没有任何键。问题是因为列表中每个元素的长度不同,它打印出一个非常难看的 table.
在此先感谢您的帮助,
嗨,我假设你想要这样的东西:
{
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
打印为:
512 2 20
512 2 20
512 2 20
512 2 20
512 2 20
您可以使用 pandas 模块来执行此操作:
import pandas as pd
a={
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
b = pd.DataFrame(a) # create a dataframe from dictionary
b.columns = ['' for _ in range(len(b.columns))] # replace column names(keys) with empty string
print(b.to_string(index=False)) # print dataframe as table but hide row indices
编辑: 要将键打印为行,您可以使用转置函数,如下所示:
import pandas as pd
a={
1: [512, 512, 512, 512, 512],
2: [2, 2, 2, 2, 2],
3: [20, 20, 20, 20, 20]
}
b = pd.DataFrame(a) # create a dataframe from dictionary
b = b.T # get transpose of b and save to b
b.columns = ['' for _ in range(len(b.columns))] # replace column names(keys) with empty string
print(b.to_string(index=False)) # print dataframe as table but hide row indices
输出应该是:
512 512 512 512 512
2 2 2 2 2
20 20 20 20 20