Reputation: 43
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.")
Upvotes: 0
Views: 121
Reputation: 71451
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']}
Upvotes: 0
Reputation: 10210
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)))
Upvotes: 2