将字典元素打印为路径列表



我正在尝试使用Floyd-Warhall算法和networkx(Python(打印所有可能的路径。问题是,我不知道如何正确执行此操作(可读,作为列表(。 我从我的图表中有这些路径:

X = nx.floyd_warshall(gra)
Y = {a: dict(b) for a, b in X.items()}
print(Y)

它返回以下内容:

{(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1, 0): {(1, 0): 0, (0, 0): 1, (1, 1): 1, (0, 1): 2, (0, 2): 3, (1, 2): 2}, (0, 1): {(0, 1): 0, (0, 0): 1, (1, 1): 1, (0, 2): 1, (1, 0): 2, (1, 2): 2}, (1, 1): {(1, 1): 0, (1, 0): 1, (0, 1): 1, (1, 2): 1, (0, 0): 2, (0, 2): 2}, (0, 2): {(0, 2): 0, (0, 1): 1, (1, 2): 1, (0, 0): 2, (1, 0): 3, (1, 1): 2}, (1, 2): {(1, 2): 0, (1, 1): 1, (0, 2): 1, (0, 0): 3, (1, 0): 2, (0, 1): 2}}

如何将其转换为更具可读性的格式?例如,是否可以逐个打印所有可能的路径?我想要这样的输出:

[(0, 0), (1, 0)]
[(1, 0), (1, 1)]
[(0, 0), (1, 0), (1, 1)]
...
[(0, 0), (1, 0), (1, 1), (0, 1), (0, 2), (1, 2)]

或者,是否可以将它们打印为 JSON(或像这样(:

{(0, 0): 
{(0, 0): 0, 
(1, 0): 1, 
(0, 1): 1, 
(1, 1): 2, 
(0, 2): 2, 
(1, 2): 3},  
(1, 0): 
{(1, 0): 0, 
(0, 0): 1, 
(1, 1): 1, 
(0, 1): 2, 
(0, 2): 3, 
(1, 2): 2}, 
[......]
(0, 1): 2}}

谢谢。。。

对于打印 Json:

import json

a = {(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1, 0): {(1, 0): 0, (0, 0): 1, (1, 1): 1, (0, 1): 2, (0, 2): 3, (1, 2): 2}, (0, 1): {(0, 1): 0, (0, 0): 1, (1, 1): 1, (0, 2): 1, (1, 0): 2, (1, 2): 2}, (1, 1): {(1, 1): 0, (1, 0): 1, (0, 1): 1, (1, 2): 1, (0, 0): 2, (0, 2): 2}, (0, 2): {(0, 2): 0, (0, 1): 1, (1, 2): 1, (0, 0): 2, (1, 0): 3, (1, 1): 2}, (1, 2): {(1, 2): 0, (1, 1): 1, (0, 2): 1, (0, 0): 3, (1, 0): 2, (0, 1): 2}}

def dict_key_convert(dic):
converted = {}
for key, item in dic.items():
if isinstance(item, dict):
sub_dict = dict_key_convert(item)
converted[str(key)] = sub_dict
else:
converted[str(key)] = item
return converted

# print(json.dumps(dict_key_convert(a), indent=2))
with open('temp.json', 'w') as file:
json.dump(dict_key_convert(a), file, indent=2)

结果:

{
"(0, 0)": {
"(0, 0)": 0,
"(1, 0)": 1,
"(0, 1)": 1,
"(1, 1)": 2,
"(0, 2)": 2,
"(1, 2)": 3
},
"(1, 0)": {
"(1, 0)": 0,
"(0, 0)": 1,
"(1, 1)": 1,
"(0, 1)": 2,
"(0, 2)": 3,
"(1, 2)": 2
},
"(0, 1)": {
"(0, 1)": 0,
"(0, 0)": 1,
"(1, 1)": 1,
"(0, 2)": 1,
"(1, 0)": 2,
"(1, 2)": 2
},
"(1, 1)": {
"(1, 1)": 0,
"(1, 0)": 1,
"(0, 1)": 1,
"(1, 2)": 1,
"(0, 0)": 2,
"(0, 2)": 2
},
"(0, 2)": {
"(0, 2)": 0,
"(0, 1)": 1,
"(1, 2)": 1,
"(0, 0)": 2,
"(1, 0)": 3,
"(1, 1)": 2
},
"(1, 2)": {
"(1, 2)": 0,
"(1, 1)": 1,
"(0, 2)": 1,
"(0, 0)": 3,
"(1, 0)": 2,
"(0, 1)": 2
}
}

最新更新