How to convert a file to a dictionary?

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

1 a 2 b 3 c 

I want to read this file in a dictionary, so 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 performance is not a problem.

+60
python dictionary file
Jan 26 '11 at 11:24
source share
8 answers
 d = {} with open("file.txt") as f: for line in f: (key, val) = line.split() d[int(key)] = val 
+101
Jan 26 '11 at 11:28
source share

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) 
+8
Jan 26 '11 at 11:27
source share

If your python version is 2.7+, you can also use a dict understanding , for example:

 with open('infile.txt') as f: {int(k): v for line in f for (k, v) in (line.strip().split(None, 1),)} 
+6
Jan 24 '13 at 1:03
source share
 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) 
+3
Jan 26 '11 at 12:50
source share

IMHO a bit more pythonic for using generators (maybe you need 2.7+ for this):

 with open('infile.txt') as fd: pairs = (line.split(None) for line in fd) res = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()} 

It also filters out lines that do not start with an integer or do not contain exactly two elements.

0
Jul 19 '13 at 9:09 on
source share

If you like one liner, try:

 d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}') 

Input FILE = file path, SEP = key separator character

Not the most elegant or effective way to do this, but nonetheless quite interesting :)

0
Jan 22 '14 at 10:16
source share

Here is another option ...

 events = {} for line in csv.reader(open(os.path.join(path, 'events.txt'), "rb")): if line[0][0] == "#": continue events[line[0]] = line[1] if len(line) == 2 else line[1:] 
0
Jul 11 '16 at 16:40
source share
 import re my_file = open('file.txt','r') d = {} for i in my_file: g = re.search(r'(\d+)\s+(.*)', i) # glob line containing an int and a string d[int(g.group(1))] = g.group(2) 
-one
Jan 26 '11 at 11:28
source share



All Articles