Reputation: 192
I have a file in the following format:
key1/value1
key2/value2
key3/value3
...
I want to read it into a dictionary. I have written a following code which accomplishes this:
with open(filename, 'r') as dir_file:
return {line.split('/')[0]: line.split('/')[1] for line in dir_file.readlines()}
However, it seems to me that invoking split()
method twice is a bad code, and there must be a simpler/better way to split the line into a key-value pair that I'm missing here.
Thank you in advance!
Upvotes: 1
Views: 3177
Reputation: 71451
You can try this:
new_dict = {a:b for a, b in [i.strip('\n').split("/") for i in open('filename.txt')]}
Upvotes: 1