如何从字典中创建一个漂亮的矩阵

时间:2013-01-03 12:46:44

标签: python dictionary matrix

我想制作一个矩阵,列出嵌套的词典。 但我无法找到如何制作矩阵,更不用说如何将我的价值放入其中。

我的字典看起来像:

    {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

它应该以矩阵排序,所以看起来像这样:

        1  2  3  4   5   6
     1  -  1  0  0   1   29
     2  13 -  1  0   21  0
     3  0  0  -  1   0   1
     4  1  17 1  -   2   0
     5  39 1  0  0   -   14
     6  0  0  43 1   0   -

我只是试图了解如何制作矩阵:

    table=[[for 0 in range(6)] for j in range[6]]
    print table
    for d1 in range(6):
        for d2 in range(6):
            table[d1][d2]=d1+d2+2
    print table

但我有一本字典,而不是列表。我真的迷路了。

8 个答案:

答案 0 :(得分:16)

import pandas as pd

a = pd.DataFrame({'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
                  '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
                  '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
                  '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
                  '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
                  '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}})

投入a

    1   2   3   4   5   6
1 NaN  13   0   1  39   0
2   1 NaN   0  17   1   0
3   0   1 NaN   1   0  43
4   0   0   1 NaN   0   1
5   1  21   0   2 NaN   0
6  29   0   1   0  14 NaN

然后可以打印成您的格式:

print a.to_string(na_rep='-')

打印:

    1   2   3  4   5   6
1   -   1   0  0   1  29
2  13   -   1  0  21   0
3   0   0   -  1   0   1
4   1  17   1  -   2   0
5  39   1   0  0   -  14
6   0   0  43  1   0   -

答案 1 :(得分:5)

使用str.format()

dic = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

strs = "{0:^2} {1:^2} {2:^2} {3:^2} {4:^2} {5:^2} {6:^2}"    

print strs.format(" ", *sorted(dic))

for x in sorted(dic):
    print strs.format(x, *(dic[x].get(y, '-') for y in sorted(dic)))

<强>输出:

   1  2  3  4  5  6 
1  -  1  0  0  1  29
2  13 -  1  0  21 0 
3  0  0  -  1  0  1 
4  1  17 1  -  2  0 
5  39 1  0  0  -  14
6  0  0  43 1  0  - 

你也可以像这样生成strs

strs = " ".join("{"+"{0}{1}".format(i, ":^2}") for i in range(7))  

答案 2 :(得分:2)

这是将在屏幕上打印矩阵的python代码。致电prettyPrint(data)

table是一个包含数据的多维数组(矩阵)。

import string

data = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

def prettyPrint(data):
    count = len(data)

    table = [[0 for x in xrange(count)] for x in xrange(count)]

    print string.ljust(' ', 4),
    for j in range(1, count + 1):
        print string.ljust(`j`, 4),
    print ""

    for i in range(1, count + 1):
        print string.ljust(`i`, 4),

        for j in range(1, count + 1):
            #print string.rjust(`j`, 4),
            if j != i:
                print string.ljust(`data[str(i)][str(j)]`, 4),
                table[i-1][j-1] = data[str(i)][str(j)]
            else:S
                print string.ljust('-', 4),
                table[i-1][j-1] = '-'
        print ""

    print "\nMatrix: \n"
    for row in table:
        print row

prettyPrint(data)

输出:

>>> 
     1    2    3    4    5    6    
1    -    1    0    0    1    29   
2    13   -    1    0    21   0    
3    0    0    -    1    0    1    
4    1    17   1    -    2    0    
5    39   1    0    0    -    14   
6    0    0    43   1    0    -    

Matrix: 

[0, 1, 0, 0, 1, 29]
[13, 0, 1, 0, 21, 0]
[0, 0, 0, 1, 0, 1]
[1, 17, 1, 0, 2, 0]
[39, 1, 0, 0, 0, 14]
[0, 0, 43, 1, 0, 0]
>>> 

答案 3 :(得分:2)

这对我有用。它不是非常pythonic,因为我不使用列表推导和那种东西,但这种方式更容易阅读和理解:

import sys

matrix = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
          '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
          '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
          '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
          '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
          '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

#print the column index
sys.stdout.write ("\t") # empty tab at the beginning
for col_index in range (1, len(matrix)+1):
    sys.stdout.write ("%d\t" % col_index)
print ""

# order the matrix rows, using the dictionary keys
for row_index in sorted (matrix.iterkeys()):
    #print the row index
    sys.stdout.write (str(row_index)+"\t")

    # take each row, and order it by its inner key:
    row = matrix[row_index]
    ordered_row = sorted (row.iterkeys())

    # iterate from 1 to number_of_matrix_rows
    for col_index in range (1, len(matrix)+1):
        # if the current column exists as a key in
        # the row, print it. Otherwise, print "-"
        row_item = "-"
        if str(col_index) in ordered_row:
            row_item = row[str(col_index)]
        sys.stdout.write (str(row_item)+"\t")

    # print next row
    print ""

答案 4 :(得分:2)

一个基于@Ashwini Chaudhary使用str.format的解决方案的函数,可以使用变量长度的字典:

def prettyPrint(d,space=5,fill='-'):
    strs = ''.join('{{{0}:^{1}}}'.format(str(i),str(space)) 
                                 for i in xrange(len(d)+1))
    std = sorted(d)
    print strs.format(" ",*std)
    for x in std:
        print strs.format(x,*(d[x].get(y,fill) for y in std)) 

prettyPrint(d)

OUT:

       1    2    3    4    5    6  
  1    -    1    0    0    1   29  
  2   13    -    1    0   21    0  
  3    0    0    -    1    0    1  
  4    1   17    1    -    2    0  
  5   39    1    0    0    -   14  
  6    0    0   43    1    0    - 

OR:

prettyPrint(d,space=3,fill='0')

OUT:

    1  2  3  4  5  6 
 1  0  1  0  0  1 29 
 2 13  0  1  0 21  0 
 3  0  0  0  1  0  1 
 4  1 17  1  0  2  0 
 5 39  1  0  0  0 14 
 6  0  0 43  1  0  0

答案 5 :(得分:1)

可能不是一个完美或最有效的解决方案,但它有效:

def printMatrix (d):
    # get the amount of characters needed for the maximum number
    numberWidth = len(str(max(max(v.values()) for v in d.values())))

    # function to format the numbers
    formatNumber = lambda x: str(x).rjust(numberWidth)

    keys = sorted(d.keys())
    rows = [' '.join(map(formatNumber, [''] + keys))]

    for r in keys:
        row = [r]
        for k in keys:
            row.append(d[r].get(k, '-'))
        rows.append(' '.join(map(formatNumber, row)))

    print('\n'.join(rows))

像这样使用:

>>> d = { ... }
>>> printMatrix(d)
      1   2   3   4   5   6
  1   -   1   0   0   1  29
  2  13   -   1   0  21   0
  3   0   0   -   1   0   1
  4   1  17   1   -   2   0
  5  39   1   0   0   -  14
  6   0   0  43   1   0   -

答案 6 :(得分:1)

以下单行可以将您的字典更改为列表(方形矩阵):

[[d[str(i)].get(str(j), '-') for j in range(1, 7)] for i in range(1, 7)]

其中d是您的输入词典。基于此,您可以轻松打印任何您想要的格式。顺便说一句,除非这是一项学校作业,否则我认为以任何具体形式进行印刷都不重要。将字典更改为类似矩阵的数据结构更有意义。如果只是为了调试,您可以使用pprint来获得更好的输出。

答案 7 :(得分:0)

这是一个没有外部库的冗长而灵活的代码,它还返回一个可用的矩阵。

dict_matrix = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
               '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
               '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
               '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
               '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
               '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

def matricize_dict(a_dict, x_size, y_size):
    matrix = []

    for i in range(y_size):
        line = []
        for j in range(x_size):
            line.append('-')
        matrix.append(line)

    for i in range(y_size):
        line = dict_matrix[str(i+1)]
        for j in range(x_size):
            try:
                cell = line[str(j+1)]
            except KeyError:
                pass
            else:
                matrix[i][j] = cell
    for item in matrix:
        print(item)

    return matrix

matricize_dict(dict_matrix, 6, 6)