Dmytro Chekunov
Dmytro Chekunov

Reputation: 192

Splitting lines read from file into dictionary key-value pairs

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

Answers (2)

Ajax1234
Ajax1234

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

ettanany
ettanany

Reputation: 19806

Use the following:

>>> with open('my_file.txt', 'r') as f:
...     d = dict(line.strip().split('/') for line in f)
...
>>>
>>> d
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

strip() is used to remove \n at the end of each line.

Upvotes: 6

Related Questions