How to convert a file into a dictionary?

I have a file comprising two columns, i.e.,

1 a 
2 b 
3 c

I wish to read this file to a dictionary such that column 1 is the key and column 2 is the value, i.e.,

d = {1:'a', 2:'b', 3:'c'}

The file is small, so efficiency is not an issue.


Solution 1:

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

Solution 2:

This will leave the key as a string:

with open('infile.txt') as f:
  d = dict(x.rstrip().split(None, 1) for x in f)

Solution 3:

You can also use a dict comprehension like:

with open("infile.txt") as f:
    d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}

Solution 4:

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)