def get_pair(line): key, sep, value = line.strip().partition(" ") return int(key), value with open("file.txt") as fd: d = dict(get_pair(line) for line in fd)
Here is what the above code is Doing:
1. The with statement opens the file and assigns the file object to the variable fd.
2. The dict() function creates a dictionary from the generator expression.
3. The generator expression is a for loop that calls get_pair() on each line in the file.
4. The get_pair() function parses the line and returns a tuple of (key, value).
5. The dict() function takes the tuples returned by the generator expression and uses them to create a dictionary.