How to convert a file into a dictionary?


Question

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.

1
80
9/30/2017 8:38:32 PM

Accepted Answer

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val
135
1/26/2011 11:28:47 AM

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon