简体   繁体   English

如何通过读取.txt文件的每一行来将键值添加到字典中并更新值?

[英]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.

相关问题 我有一个txt文件。 如何获取字典键值并打印出现在其中的文本行? - I have a txt file. How can I take dictionary key values and print the line of text they appear in? 从文件中读取并添加到字典中时,如何将值添加到键中 - how can I add the values to the key when read from file and add into dictionary 如何从字典中的文件中将相同键的值相互添加? - How can I add the values of the same key to one another from a file within a dictionary? 如何通过读取.txt文件为每个键创建包含多个“列表”的Python字典? - How to create Python dictionary with multiple 'lists' for each key by reading from .txt file? 如何获得字典中每个键的值长度? - How can I get lengths of values for each of the key in a dictionary? 如何读取一个txt文件并创建一个字典,每个键都具有python中的值列表? - How to read a txt file and create a dictionary with each key having list of values in python? 如何从文件中将值添加到现有的空值键字典? - How to add values to an existing empty value key dictionary from a file? 如何使用正在读取的文本文件中的值创建python字典 - How can I create a python dictionary using values from a text file that I'm reading in 从字典字典中读取特定的键值 - Reading specific key values from a dictionary of dictionary 使用键和值将文件添加到字典 - Add a file to dictionary with key and values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM