Pydronia
Pydronia

Reputation: 21

Create a dictionary w/ list comprehension from a file

Say I have this code:

someDict = {}
for line in open("example.txt"):
  key, val = line.strip().split(",")
  someDict[key] = val

with example.txt being two pieces of data on each line, separated by a comma, for example:

one,un
two,deux
three,trois

etc.

This works in making a dictionary, however I am curious if this could be accomplished in one line (eg with list/dictionary comprehension). Is this possible, or an otherwise shorter/easier way to do this?

Upvotes: 1

Views: 667

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122392

Yes, you can do it with a generator expression and the dict() callable:

with open('example.txt') as fileobj:
    someDict = dict(line.strip().split(',', 1) for line in fileobj)

I limited the splitting to just once; this allows the value to contain commas and not break the expression.

The dict() callable takes a sequence of (key, value) pairs, so splitting a line to exactly two elements satisfies that requirement exactly.

I used a with statement to handle the file object; it makes sure the file is closed again after reading has completed or an exception is raised.

It could be done with a dictionary comprehension as well, but that usually gets quite ugly as you'd have to use an additional single-element loop to extract the key-value pair, or split the line twice.

Upvotes: 7

Related Questions