简体   繁体   中英

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. If I had a .txt file like this:

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:

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM