0

I have a .txt file that looks like this:

Key1    Key2    Key3
Val1-A  Val2-A  Val3-A
Val1-B  Val2-B  Val3-B
....

Each field is separated by tab, how can I read the file and store it in a dictionary of lists without using any kind of for/while loop? Comprehensions are allowed

with open("file.txt", "r") as input:
    #comprehension here

Thanks!

EDIT: sorry I forgot to include my attempt so far

 try:
    with open("file.txt", "r") as input:
        line = input.readline()
        line = re.split(r '\t+', line)
        myDict = dict(line.strip() for line in infile)
        if line == "":
            raise ValueError            
 except IOError:
    print ("Error! File is not found.")
 except ValueError:
    print("Error! File is empty.")
Gus
  • 43
  • 7
  • Possible duplicate of [Creating a dictionary from a CSV file](https://stackoverflow.com/questions/14091387/creating-a-dictionary-from-a-csv-file) – Maurice Meyer Jan 13 '18 at 18:10
  • Also sounds like homework. Please show what you've tried. Stack Overflow is not a code writing service. – Adam Brinded Jan 13 '18 at 18:12
  • @MauriceMeyer the solutions for that one uses loops, I am looking for a solution that doesn't use one – Gus Jan 13 '18 at 18:12
  • @AdamBrinded yes it is a HW, sorry! I included my attempt – Gus Jan 13 '18 at 18:19
  • [Why “Can someone help me?” is not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – wwii Jan 13 '18 at 18:32
  • Are you getting any errors? You should fix those and repost the fixed code. Or ask specific question(s) about the errors you are getting. – wwii Jan 13 '18 at 18:36

2 Answers2

2

Check this:

with open("file.txt", "r") as input:
    keys = input.readline().split()
    values = [line.split() for line in input.readlines()]
    result = dict(zip(keys, zip(*values)))
Tomáš Linhart
  • 9,832
  • 1
  • 27
  • 39
0

Below are two possible solutions which structure the data similar to what you described:

data = [i.strip('\n').split('\t') for i in open('filename.txt')]
new_data = [dict(zip(data[0], i)) for i in data[1:]]

Output:

[{'Key3': 'Val3-A', 'Key2': 'Val2-A', 'Key1': 'Val1-A'}, {'Key3': 'Val3-B', 'Key2': 'Val2-B', 'Key1': 'Val1-B'}]

Or:

new_data = {a:list(b) for a, b in zip(data[0], zip(*data[1:]))}

Output:

{'Key3': ['Val3-A', 'Val3-B'], 'Key2': ['Val2-A', 'Val2-B'], 'Key1': ['Val1-A', 'Val1-B']}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102