简体   繁体   中英

Python - reading file to dictionary

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.")

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)))

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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM