Reputation: 1395
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.
Upvotes: 0
Views: 9092
Reputation: 55
The following code has worked for me.
# Initialize a dictionary
dict = {}
# Feed key-value pairs to the dictionary
dict['name'] = "Gautham"
dict['stay'] = "Bangalore"
dict['study'] = "Engineering"
dict['feeling'] = "Happy"
# Open the text file "text.txt", whose contents are:
####################################
## what is your name
## where do you stay
## what do you study
## how are you feeling
####################################
textfile = open("text.txt",'rb')
# Read the lines of text.txt and search each of the dictionary keys in every
# line
for lines in textfile.xreadlines():
for eachkey in dict.keys():
if eachkey in lines:
print lines + " : " + dict[eachkey]
else:
continue
# Close text.txt file
textfile.close()
Upvotes: 1
Reputation: 612993
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')
Upvotes: 2