Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
Darren J. Fitzpatrick Avatar asked Jan 26 '11 11:01

Darren J. Fitzpatrick


1 Answers

d = {} with open("file.txt") as f:     for line in f:        (key, val) = line.split()        d[int(key)] = val 
like image 141
Vlad H Avatar answered Oct 09 '22 11:10

Vlad H