简体   繁体   中英

Reading a file and storing contents into a dictionary - Python

I'm trying to store contents of a file into a dictionary and I want to return a value when I call its key. Each line of the file has two items (acronyms and corresponding phrases) that are separated by commas, and there are 585 lines. I want to store the acronyms on the left of the comma to the key, and the phrases on the right of the comma to the value. Here's what I have:

def read_file(filename):

    infile = open(filename, 'r')

    for line in infile:
        line = line.strip() #remove newline character at end of each line
        phrase = line.split(',')
        newDict = {'phrase[0]':'phrase[1]'}

    infile.close()

And here's what I get when I try to look up the values:

>>> read_file('acronyms.csv')
>>> acronyms=read_file('acronyms.csv')
>>> acronyms['ABT']
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    acronyms['ABT']
TypeError: 'NoneType' object is not subscriptable
>>> 

If I add return newDict to the end of the body of the function, it obviously just returns {'phrase[0]':'phrase[1]'} when I call read_file('acronyms.csv') . I've also tried {phrase[0]:phrase[1]} (no single quotation marks) but that returns the same error. Thanks for any help.

def read_acronym_meanings(path:str):
    with open(path) as f:
        acronyms = dict(l.strip().split(',') for l in f)
    return acronyms
def read_file(filename):
    infile = open(filename, 'r')
    newDict = {}
    for line in infile:
        line = line.strip() #remove newline character at end of each line
        phrase = line.split(',', 1) # split max of one time
        newDict.update( {phrase[0]:phrase[1]})
    infile.close()
    return newDict

Your original creates a new dictionary every iteration of the loop.

First off, you are creating a new dictionary at every iteration of the loop. Instead, create one dictionary and add elements every time you go over a line. Second, the 'phrase[0]' includes the apostrophes which turn make it a string instead of a reference to the phrase variable that you just created.

Also, try using the with keyword so that you don't have to explicitly close the file later.

def read(filename):
    newDict = {}
    with open(filename, 'r') as infile:
        for line in infile:
            line = line.strip() #remove newline character at end of each line
            phrase = line.split(',')
            newDict[phrase[0]] = phrase[1]}

    return newDict

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