[英]How can I add key values into a dictionary from reading in each line of a .txt file and update values?
I'm kind of new to python so I'm trying pick it up. 我是python的新手,所以我想尝试它。 If I had a
.txt
file like this: 如果我有一个
.txt
文件,例如:
A B
A C
A E
B D
C D
C F
D G
F C
G H
And I read in the .txt
file line by line with: 我逐行读入
.txt
文件:
with open(txtFile) as file:
for line in file:
I want it so that if the letter doesnt exist, then create it but if it does, itll add the letter it connects to, onto that existing letter. 我想要它,以便如果该字母不存在,则创建它,但是如果存在,则将它连接到的字母添加到该现有字母上。 How would I be able to create a dictionary that maps everything so it ends up looking like this:
我将如何创建一个映射所有内容的字典,使其最终看起来像这样:
graph = {
'A': ['B', 'C', 'E'],
'B': ['D'],
'C': ['D', 'F'],
'D': ['G'],
'F': ['C'],
'G': ['H']
}
This is basically all I have right now: 这基本上就是我现在所拥有的:
graph = {}
with open(txtFile) as file:
for line in file:
line.split()
graph.append
I dont know how to actually add keys into the dictionary. 我不知道如何将键实际添加到字典中。 But I guess once the keys are in I can just use something like:
但是我想一旦钥匙插入,我就可以使用类似以下的命令:
graph['A'].append(line[1])
right? 对? Also, would I have to use a snippet of code that traverses all the keys in the dictionary in order to see if that key already exists?
另外,我是否必须使用遍历字典中所有键的代码片段来查看该键是否已经存在? Or will duplicates just not work?
还是重复只是行不通?
Try this (not tested code): 试试这个(未经测试的代码):
from collections import defaultdict
graph = defaultdict(list)
with open(txtFile) as file:
for line in file:
s_line = line.split()
graph[s_line[0]].append(s_line[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.