0

I have a file comprising three columns, i.e. a 1 4 b 2 5 c 3 6 I wish to read this file to a dictionary so that column 1 is the key and column 2 and 3 is the value, i.e.,

dict = {'a': (1,4), 'b': (2,5), 'c': (3,6)}

Does anyone have a command for this?

home
  • 12,468
  • 5
  • 46
  • 54
Alexander West
  • 81
  • 1
  • 1
  • 9

1 Answers1

5

It is the same as the one in the link you mentioned in the comments. Except you unpack three values in a line instead of two.

test.txt (your text file)

a 1 4
b 2 5
c 3 6

Your code:

d = {}
with open("test.txt") as f:
    for line in f:
       (key, val1, val2) = line.split()
       d[key] = (int(val1), int(val2))

print(d)

gives you,

{'a': (1, 4), 'b': (2, 5), 'c': (3, 6)}
RPT
  • 728
  • 1
  • 10
  • 29