我想从节点对列表及其权重中创建字典数组的字典。
nets = pd.read_table('data/nodes.txt', header = None)
bb = np.array(nets).tolist()
graph = collections.defaultdict(dict)
for row in bb:
graph[row[0]][row[1]]=row[2]
graph[row[1]][row[0]] = row[2]
print(dict(graph))
导致了这本词典
{0: {1: 2, 2: 3, 3: 6, 7: 8}, 1: {0: 2, 2: 5, 4: 7}, 2: {0: 3, 1: 5, 11: 5, `5: 4}, 3: {0: 6, 11: 4, 6: 2}, 4: {1: 7}, 5: {8: 3, 2: 4}, 6: {9: 3, 3: 2}, 7: {0: 8}, 8: {5: 3}, 9: {10: 6, 6: 3}, 10: {9: 6}, 11: {2: 5, 3: 4}}`
并希望以此形式使用它。
{0: [{1: 2}, {2: 3}, {3: 6}, {7: 8}],
1: [{0: 2}, {2: 5}, {4: 7}],
2: [{0: 3}, {1: 5}, {11: 5}, {5: 4}],
3: [{0: 6}, {11: 4}, {6: 2}],
4: [{1: 7}],
5: [{8: 3}, {2: 4}],
6: [{9: 3}, {3: 2}],
7: [{0: 8}, 8: {5: 3}],
9: [{10: 6}, {6: 3}],
10: [{9: 6}],
11: [{2: 5}, {3: 4}]}
答案 0 :(得分:0)
如果你真的想要,你可以很容易地做到这一点,虽然我会仔细查看你将使用这个数据结构的位置,看看你现有的更合理的结构是否可以制作而是工作。
无论如何,这是一个应该做你想做的快速实现:
graph = collections.defaultdict(list)
for row in bb:
graph[row[0]].append({row[1]: row[2]})
graph[row[1]].append({row[0]: row[2]})