[英]How to read a txt file in python and output a dictionary with associating each word with a key outside txt file
I'm reading a txt file which is of form我正在阅读一个格式为 txt 的文件
apple, 1234, 156789086654, cat, John
orange, 7654, 8268249252745, dog, Smith
mango, 3467, 8328627427, cow, Alice
I have a dictionary of key_fields associating keys with value type我有一个 key_fields 字典,将键与值类型相关联
key_fields = { fruit : str
num : int
date : long
animal : str
name : str }
I want to create a final dictionary from txt file and key_fields, where each attribute from each line in txt file is mapped to the key_fields like this, with appropriate type of value fields matching the dict key_fields -我想从 txt 文件和 key_fields 创建一个最终字典,其中 txt 文件中每一行的每个属性都映射到这样的 key_fields,并具有与 dict key_fields 匹配的适当类型的值字段 -
{ fruit: "apple", num : 1234, date : 156789086654, animal : "cat", name : "John" }
{ fruit: "orange", num: 7654, date: 8268249252745, animal : "dog", name : "Smith"}
{ fruit: "mango", num: 3467, date : 8328627427, animal: "cow", name: "Alice" }
As an example with just one entry:例如,只有一个条目:
line_1 = "apple, 1234, 156789086654, cat, John"
key_fields = {
"fruit": str,
"num": int,
"date": int,
"animal": str,
"name": str
}
result_dict = {key: builder(data) for ((key, builder), data) in zip(key_fields.items(), line_1.split(", "))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.