简体   繁体   中英

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

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 = { 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 -

{ 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(", "))}

Playground

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