如何将字典转换为python中的矩阵?

时间:2019-06-08 15:44:27

标签: python dictionary matrix

我有一个像这样的字典,(i,j):数字。 (i和j是字母):

{(N,M):10,(N,K):1(H,K):13 ...}

如何创建如下所示的二维矩阵:

   N   K   M   H

N  1   -   -   -

K  1   10  -   -

M  10  12  15  -

H  4   13  6   2

2 个答案:

答案 0 :(得分:0)

目前尚不清楚您需要哪种2D数组类型,但是如果您想将字母作为索引,也许熊猫是最好的选择。

data = {('N', 'M'): 10, ('N', 'K'): 1, ('H', 'K'): 13}
keys = ['N', 'K', 'M', 'H']

import pandas as pd
matrix = pd.DataFrame(columns=keys, index=keys)
for p in pos:
    matrix.loc[p[0], p[1]] = pos[p]

如果没有字母,也可以用numpy来实现。

import numpy as np
matrix = np.zeros((len(keys), len(keys)))
for d in data:
    i = keys.index(d[0])
    j = keys.index(d[1])
    matrix[i, j] = data[d]

如果必须仅使用python的内置对象,则可以创建带有列表的矩阵。

matrix = [[None] * len(keys) for i in range(len(keys))]
for d in data:
    i = keys.index(d[0])
    j = keys.index(d[1])
    matrix[i][j] = data[d]

最后,您也可以看看其他question,但恐怕那里的解决方案无法将字母用作索引。

答案 1 :(得分:0)

这是仅使用内置Python工具完成此操作的一种方法:

letters = 'NKMH'
data = {('N', 'N'): 1,
        ('K', 'N'): 1, ('K', 'K'): 1,
        ('M', 'N'): 10, ('M', 'K'): 12, ('M', 'M'): 15,
        ('H', 'N'): 4, ('H', 'K'): 13, ('H', 'M'): 6, ('H', 'H'): 2}

# Dictionaries to make translating between letters <-> indices easy.
letter_to_index = dict(zip(letters, range(len(letters))))
index_to_letter = dict(zip(range(len(letters)), letters))

# Preallocate matrix.
matrix = [['-' for _ in range(len(letters))]
            for _ in range(len(letters))]

# Place data into the matrix.
for (row, col), value in data.items():
    i, j = letter_to_index[row], letter_to_index[col]
    matrix[i][j] = value

# Pretty print result.
print('  ', '   '.join(letters))
for i, row in enumerate(matrix):
    print('{}  {}'.format(
        index_to_letter[i], '  '.join('{:<2}'.format(value) for value in row)))

输出:

   N   K   M   H
N  1   -   -   - 
K  1   1   -   - 
M  10  12  15  - 
H  4   13  6   2