Python Forum
reading a file int a dictionary specifically - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: reading a file int a dictionary specifically (/thread-16181.html)



reading a file int a dictionary specifically - sonicx05 - Feb-17-2019

Im relatively new to python and I have a file containing words/lines like this:


AA EY2 EY1
AAA T R IH2 P AH0 L EY1
AABERG AA1 B ER0 G
AACHEN AA1 K AH0 N
AACHENER AA1 K AH0 N ER0
AAH AA1
AAKER AA1 K ER0
AALIYAH AA2 L IY1 AA2
AALSETH AA1 L S EH0 TH
AAMODT AA1 M AH0 T
AANCOR AA1 N K AO2 R

what i need to do read these into a dictionary with the key being the first word/entry of each line, and that is mapped to a list containing each string. for example- AA: "EY2", "EY1"
that way i can search for two words (indexes of the dictionary) and compare their lists. I've got a basic loop to read the file line by line stripping the newline character but not sure how to precede.

 
    d= {}
    with open(fName) as f:
        while True:
            line = f.readline()
            if not line.startswith(";;;"):
                break
        for line in f:
            print(line, end="")
i feel its important to recognize that after each of the first words in every line theres a double space. not just a single space. which has me a little tripped up since my first instinct was to use .split


RE: reading a file int a dictionary specifically - woooee - Feb-17-2019

Eliminate everything under the while True (what is this supposed to do). Print anything in the code below that you do not understand.
d= {}
with open(fName) as f:
    for line in f:
        print(line, end="")
        line_as_list=line.strip().split()
        this_key=line_as_list[0]  ## easier to understand this way??
        d[this_key]=[]
        for item in line_as_list[1:]  ## skip key/first item
            d[this_key].append(item) 



RE: reading a file int a dictionary specifically - sonicx05 - Feb-17-2019

that first part is because theres a comment in the beginning of the file and that works around it.


RE: reading a file int a dictionary specifically - woooee - Feb-18-2019

Then "for line in f" will read the next record, skipping over the while True record, no matter what the while True record contains. Just add a test
d= {}
with open(fName) as f:
    for line in f:
        print(line, end="")
        if not line.strip().startswith(";"):
            line_as_list=line.strip().split()
            this_key=line_as_list[0]  ## easier to understand this way??
            d[this_key]=[]
            for item in line_as_list[1:]  ## skip key/first item
                d[this_key].append(item)