[英]Python - reading file to dictionary
I have a .txt file that looks like this: 我有一个.txt文件,看起来像这样:
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? 每个字段都由制表符分隔,如何在不使用任何for / while循环的情况下读取文件并将其存储在列表字典中? 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']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.