Alireza Alireza - 14 days ago 9
Python Question

importing from a text file to a dictionary

filename:

dictionary.txt


YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby’s:BID
inBev:BUD


code:

infile = open('dictionary.txt', 'r')
content= infile.readlines()
infile.close()

counters ={}
for line in content:
counters.append(content)
print(counters)


i am trying to import contents of the file.txt to the dictionary. I have searched through stack overflow but please an answer in a simple way (not with open...)

Answer

First off, instead of opening and closing the files explicitly you can use with statement for opening the files which, closes the file automatically at the end of the block.

Secondly, as the file objects are iterator-like objects (one shot iterable) you can loop over the lines and split them with : character. You can do all of these things as a generator expression within dict function:

with open('dictionary.txt') as infile:
    my_dict = dict(line.strip().split(':') for line in infile)
Comments