Python 如何将词典插入空词典?
我正在使用BFS算法,我有这个代码的输出Python 如何将词典插入空词典?,python,arrays,algorithm,dictionary,Python,Arrays,Algorithm,Dictionary,我正在使用BFS算法,我有这个代码的输出 > for node in graph.keys(): > print(BFS(graph, node)) 输出 {1: 0, 6: 1, 7: 2, 2: 3, 8: 4, 3: 5, 4: 6, 9: 7, 5: 8, 10: 9} {2: 0, 8: 1, 3: 2, 4: 3, 9: 4, 5: 5, 10: 6, 1: -1, 6: -1, 7: -1} {3: 0, 4: 1, 9: 2, 5: 3, 1
> for node in graph.keys():
> print(BFS(graph, node))
输出
{1: 0, 6: 1, 7: 2, 2: 3, 8: 4, 3: 5, 4: 6, 9: 7, 5: 8, 10: 9}
{2: 0, 8: 1, 3: 2, 4: 3, 9: 4, 5: 5, 10: 6, 1: -1, 6: -1, 7: -1}
{3: 0, 4: 1, 9: 2, 5: 3, 10: 4, 1: -1, 2: -1, 6: -1, 7: -1, 8: -1}
{4: 0, 9: 1, 5: 2, 10: 3, 1: -1, 2: -1, 3: -1, 6: -1, 7: -1, 8: -1}
{5: 0, 10: 1, 1: -1, 2: -1, 3: -1, 4: -1, 6: -1, 7: -1, 8: -1, 9: -1}
{6: 0, 7: 1, 2: 2, 8: 3, 3: 4, 4: 5, 9: 6, 5: 7, 10: 8, 1: -1}
{7: 0, 2: 1, 8: 2, 3: 3, 4: 4, 9: 5, 5: 6, 10: 7, 1: -1, 6: -1}
{8: 0, 3: 1, 4: 2, 9: 3, 5: 4, 10: 5, 1: -1, 2: -1, 6: -1, 7: -1}
{9: 0, 5: 1, 10: 2, 1: -1, 2: -1, 3: -1, 4: -1, 6: -1, 7: -1, 8: -1}
{10: 0, 1: -1, 2: -1, 3: -1, 4: -1, 5: -1, 6: -1, 7: -1, 8: -1, 9: -1}
我需要将这些字典添加到一个字典中,如下所示
dic = {
1: {1: 0, 6: 1, 7: 2, 2: 3, 8: 4, 3: 5, 4: 6, 9: 7, 5: 8, 10: 9},
2: {2: 0, 8: 1, 3: 2, 4: 3, 9: 4, 5: 5, 10: 6, 1: -1, 6: -1, 7: -1},
3: {3: 0, 4: 1, 9: 2, 5: 3, 10: 4, 1: -1, 2: -1, 6: -1, 7: -1, 8: -1},
4: {4: 0, 9: 1, 5: 2, 10: 3, 1: -1, 2: -1, 3: -1, 6: -1, 7: -1, 8: -1},
5: {5: 0, 10: 1, 1: -1, 2: -1, 3: -1, 4: -1, 6: -1, 7: -1, 8: -1, 9: -1},
6: {6: 0, 7: 1, 2: 2, 8: 3, 3: 4, 4: 5, 9: 6, 5: 7, 10: 8, 1: -1},
7: {7: 0, 2: 1, 8: 2, 3: 3, 4: 4, 9: 5, 5: 6, 10: 7, 1: -1, 6: -1},
8: {8: 0, 3: 1, 4: 2, 9: 3, 5: 4, 10: 5, 1: -1, 2: -1, 6: -1, 7: -1},
9: {9: 0, 5: 1, 10: 2, 1: -1, 2: -1, 3: -1, 4: -1, 6: -1, 7: -1, 8: -1},
10: {10: 0, 1: -1, 2: -1, 3: -1, 4: -1, 5: -1, 6: -1, 7: -1, 8: -1, 9: -1}
}
我假设创建一个空字典,并将节点添加为键,将代码的输出添加为值。但它不起作用
谢谢试试这个:
dic = {}
for num, node in enumerate(graph.keys()):
dic[num] = BFS(graph, node)
print(BFS(graph, node))
仅使用听写理解:
{node:BFS(graph, node) for node in graph.keys()}
res = {i + 1: BFS(graph, node) for i, node in enumerate(graph.keys())}
您可以应用
enumerate()
来使用dict comprehension生成dict
:
{node:BFS(graph, node) for node in graph.keys()}
res = {i + 1: BFS(graph, node) for i, node in enumerate(graph.keys())}
哎哟,我错过了你想用
节点
作为dict键的机会。@Andrei已经用代码回答了这个问题。完美兄弟,谢谢。我能问你点别的吗?我在这本词典中应用了pandas,但是输出的行看起来是无序的(1,6,3,5,4等等),你知道如何排序吗?@Andres,将graph.keys()
替换为sorted(graph.keys())
@Andres dict不能保证顺序,所以你需要对pandas行进行排序,你是对的,我必须在pandas中进行排序。谢谢