Captain_Harlock
Captain_Harlock

Reputation: 13

File Columns to Dictionary

Hello I have a file comprising 4 columns,

a  1  45  test
b  2  42  test
c  3  64  test

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

d = {45:'a', 42:'b', 64:'c'}

Upvotes: 0

Views: 57

Answers (2)

wwii
wwii

Reputation: 23773

Keep it simple:

>>> 
>>> d = dict()
>>> with open('test.txt') as f:
    for line in f:
        val, foo, key, bar = line.split()
        d[key] = val


>>> d
{'64': 'c', '45': 'a', '42': 'b'}
>>> 

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 12092

Use the csv module to parse the file. Change the delimiter parameter to whatever is the delimiter in your input file. I have assumed it to be tabs.

import csv
d = {}
with open('your-input-file', 'r') as input_file:
    csv_reader = csv.reader(input_file, delimiter='\t')
    for row in csv_reader:
        d[row[2]] = row[0]
input_file.close()

Upvotes: 0

Related Questions