如何使用字典的值来获取输出表?

时间:2017-10-23 12:46:11

标签: python dictionary

dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], ' Sally': [7,8,9]}

我想要的是绘制一个表格,其中第一行中的名称和每个名称下的成绩,我希望它是动态的。基本上,我不必干涉字典中的内容(如精确的确切名称),只读取其中的每个键。

我尝试了以下内容:

for x in range(size):
        table.append(dictionary[x])
        table.append(int(100 - 100 * dictionary[x] / B),)

for x in range (size*2+2):
    values.append(np.array(np.array(table[1:])[:, x+1],dtype=np.float32))

请注意,100存在是因为在实际代码中,数字基本上用于获得百分比除以B,而在size*2+2中,因为我添加了其他字符但赢了&我问这个问题。

(运行python2.7)

2 个答案:

答案 0 :(得分:0)

所以这听起来像是一个家庭作业问题......我会给你一些帮助,但你也需要做一些工作。
这是制作一个表格的方法,其中第一行打印每个人的姓名,名称下面将是该学生的成绩。 (Python 3.6)

dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], 'Sally': [7,8,9]}
print("%s" % dictionary)

# print the names of the students
for key in dictionary:
    print("%s" % ('{0:%ds}' % (len(key) + 2)).format(key), end="")
print()

# print the grades under each student
i = 0
keys = list(dictionary.keys())

while i < len(keys):    
    j = 0
    while j < len(keys):
        values = list(dictionary.values())
        print("%s  " % ('{0:%dd}' % (len(keys[j]))).format(values[j][i]), end="")
        j = j + 1
    print()
    i = i + 1

输出:

{'Alex': [1, 2, 3], 'Tim': [4, 5, 6], 'Sally': [7, 8, 9]}
Alex  Tim  Sally  
   1    4      7  
   2    5      8  
   3    6      9  

希望这有帮助

答案 1 :(得分:0)

正如@Dadep在评论中所说,你可以用这种方式将你的字典加载到pandas DataFrame中:

import pandas as pd
import numpy as np
dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], 'Sally': [7,8,9]}
df = pd.DataFrame.from_dict(dictionary)

DataFrame是一个表格,您可以对其列进行操作。如果您打印它,我们创建的那个看起来像这样:

   Alex  Sally  Tim
0     1      7    4
1     2      8    5
2     3      9    6

我不确定您要执行什么操作,但我会举例说明如何添加列或编辑列:

B = 10
df["Alex"] = (100 - 100 * df["Alex"] / B).apply(np.int64)   # Edit Alex column
df["Sally2"] = (100 - 100 * df["Sally"] / B).apply(np.int64)   # Make new Sally2 column

然后表格如下:

   Alex  Sally  Tim     Sally2
0    90      7    4         30
1    80      8    5         20
2    70      9    6         10

请注意,如果您将使用pandas,则所有列都需要具有相同的长度。