一个更 numpythonic 的版本......这些值存储为字符串。这可以更改,但您可能需要更好地定义输入字典列表的语法:
import numpy as np
import operator as op
data = [('x', {'y' : '1,3', 'z' : '2'}),
('y', {'a' : '4'}),
('z', {'b' : '2,3'})]
keys = np.array(['x', 'y', 'z', 'a', 'b'])
keys_sort = np.argsort(keys)
rows = [(item[0], item[1].keys(), item[1].values()) for item in data]
rows = np.array(reduce(op.add, ([item[0]]*len(item[1]) for item in data)))
cols = np.array(reduce(op.add, (item[1].keys() for item in data)))
vals = np.array(reduce(op.add, (item[1].values() for item in data)))
row_idx = keys_sort[np.searchsorted(keys, rows, sorter=keys_sort)]
col_idx = keys_sort[np.searchsorted(keys, cols, sorter=keys_sort)]
out_arr = np.empty((len(keys), len(keys)), dtype=vals.dtype)
out_arr[:] = '0'
out_arr[row_idx, col_idx] = vals
out_arr[col_idx, row_idx] = vals
>>> out_arr
array([['0', '1,3', '2', '0', '0'],
['1,3', '0', '0', '4', '0'],
['2', '0', '0', '0', '2,3'],
['0', '4', '0', '0', '0'],
['0', '0', '2,3', '0', '0']],
dtype='|S3')