PYTHON: Read a file into a dictionary with column n as key and column m as value

dictionarypython

I know how to do it if its just two columns, but what if the file is like:

01 asd 023 green
01 dff 343 blue
02 fdf 342 yellow
02 fff 232 brown
02 kjf 092 green
03 kja 878 blue

and say, I would like column 2 to be the key to my dictionary and column 4 to my content for that key? I was thinking, a way to go around this problem would be to totally delete the other useless columns so that only the two I need remain, then I can use a script which I also saw on this website to make the dictionary

Python – file to dictionary?

Of course, this is a way around the problem, any tip is greatly appreciated.

Best Answer

d = {}
with open('data.txt') as f:
  for line in f:
    tok = line.split()
    d[tok[1]] = tok[3]
print(d)

This produces

{'kja': 'blue', 'kjf': 'green', 'fdf': 'yellow', 'asd': 'green', 'fff': 'brown', 'dff': 'blue'}

split() (without an argument) splits the lines into lists of strings. tok[1] and tok[3] then use list indexing to address the second and fourth values in those lists, assigning them to a dictionary's keys and values (d[key] = value).