English Grad English Grad - 1 year ago 46
Python Question

Reading a text file and matching it to a dictionary key in python

I have a dictionary made in python. I also have a text file where each line is a different word. I want to check each line of the text file against the keys of the dictionary and if the line in the text file matches the key I want to write that key's value to an output file. Is there an easy way to do this. Is this even possible? I am new to programming and cannot quite get a handle of how to access the dictionaries. Thank-you for the help.

Answer Source

Read a file line by line like this:

with open(filename, 'r') as f:
    for line in f:
        value = mydict.get(line.strip())
        if value is not None:
            print value

This prints each value to standard output. If you want to output to a file it would be like this:

with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
    for line in infile:
        value = mydict.get(line.strip())
        if value is not None:
            outfile.write(value + '\n')