Python3:如何根据元组字典生成表

时间:2018-07-13 12:51:21

标签: python dictionary

我有一个以元组为键的dict,例如:

my_dict = {('A1', 'A2'): 0.6, ('A1', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}

我想打印一张桌子,

Table   A1    A2 
A1      1     0.6
A2      0.3   1

不使用熊猫如何处理此问题?我只是不想导入未内置在python中的模块。

3 个答案:

答案 0 :(得分:1)

一种更通用的解决方案,避免使用硬编码并为丢失的数据填充“ NA”:

my_dict = {('A1', 'A2'): 0.6, ('A3', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}

labs = []
for key in my_dict.keys():
    for k in key:
        if k not in labs:
            labs.append(k)
labs = sorted(labs)

print("Table\t" + "\t\t".join(labs))
for i in labs:
    print(i, end="\t\t")
    for j in labs:
        try:
            print(my_dict[(i, j)], end="\t\t")
        except KeyError:
            print("NA", end="\t\t")
    print()

输出:

Table   A1      A2      A3
A1      NA      0.6     NA      
A2      0.3     1       NA      
A3      1       NA      NA      

答案 1 :(得分:0)

print("Table  A1   A2")
for i in ['A1','A2']:
    print(i, end= "     ")
    for j in ['A1','A2']:
        print(my_dict[(i,j)], end = "   ")
    print()

输出

Table  A1   A2
A1     1   0.6   
A2     0.3   1  

答案 2 :(得分:0)

您可以使用列表理解:

my_dict = {('A1', 'A2'): 0.6, ('A1', 'A1'): 1, ('A2', 'A2'): 1, ('A2', 'A1'): 0.3}
table = [[[c for [d1, d2], c in my_dict.items() if f'A{i}' == d2 and f'A{b}' == d1][0] 
   for i in range(1, 3)] for b in range(1, 3)]
top = 'table  {}'.format(' '.join(f'A{i}' for i in range(1, len(max(table, key=len))+1)))
final = '{}\n{}'.format(top, '\n'.join(f'A{i}    {" ".join(map(str, a))}' for i, a in enumerate(table)))

输出:

table  A1 A2
A0    1 0.6
A1    0.3 1