2

I would like to define a dictionary using the 2 first columns of a text file (with a tab delimiter).

Using the following code, I create a dictionary "dict" in which the keys are the rows in the first column and the values are the rows in the second and third columns:

mydict = {}
with open("myfile.txt") as f:
    mydict = dict(x.split(" ", 1) for x in f)

However, I would like to discard the third column and use the first column as a key and the second as a value in the dictionary "dict". I tried this code but it does not work for me:

mydict = {}
with open("myfile.txt") as f:
    mydict = dict(x.split(" ", 2)[0:1] for x in f)

Any suggestions are welcome, thanks!

Charlie
  • 49
  • 3
  • You can't call your dictionary `dict` and still use `dict()`, you are shadowing the built-in type. – Martijn Pieters Feb 26 '19 at 11:10
  • Your slice only selects **one** of the split results. If you want the first two elements, use `[0:2]` or `[:2]` (equivalent). – Martijn Pieters Feb 26 '19 at 11:11
  • Side note: I'd use the CSV module for this: `reader = csv.reader(f, delimiter='\t')`, then `result = dict(row[:2] for row in reader)` or, with an additional `from operator import itemgetter`, use `result = dict(map(itemgetter(0, 1), reader))`. – Martijn Pieters Feb 26 '19 at 11:13

0 Answers0