Python 使用混合键值创建字典的文件

Python 使用混合键值创建字典的文件,python,file,python-3.x,dictionary,graph,Python,File,Python 3.x,Dictionary,Graph,您好,我有一个格式如下的文件: 1 5 2 6 3 6 4 5 5 6 5 7 5 8 ... 我想做一本这样的字典: 1:5 2:6 3:6 4:5 5: 1, 4, 6, 7, 8 6: 2, 3, 5, .... 该文件是无向图的节点之间的连接,我想将其转换为一个字典,其中节点作为键,该节点的邻居作为值(邻接列表) 我的问题是,我不知道如何从文件中检索数据,以便将节点与其所有邻居匹配 我试过这个 nodeList = list() with open(file) as inputfil

您好,我有一个格式如下的文件:

1 5
2 6
3 6
4 5
5 6
5 7
5 8
...
我想做一本这样的字典:

1:5
2:6
3:6
4:5
5: 1, 4, 6, 7, 8
6: 2, 3, 5,
....
该文件是无向图的节点之间的连接,我想将其转换为一个字典,其中节点作为键,该节点的邻居作为值(邻接列表)

我的问题是,我不知道如何从文件中检索数据,以便将节点与其所有邻居匹配

我试过这个

nodeList = list()
with open(file) as inputfile:
    for line in inputfile.readlines():
        nodeList.append(tuple(line.strip().split()))

d = defaultdict(list)
for k, v in nodeList:
    d[k].append(v)
结果就是一本字典:

但它并不完全正确,因为例如,我希望
4
1
显示为键
5
中的值

d = defaultdict(list)
for k, v in nodeList:
    d[k].append(v)
    d[v].append(k)
给我想要的结果。 谢谢你帮我