简体   繁体   中英

Create a dictionary with a fixed set of keys from reading text file in Python

Input: - A text file that contains 3 lines:

"Thank you
binhnguyen
2010-09-12
I want to say thank you to all of you."

Output: I want to create a dictionary with fixed keys: 'title', 'name', 'date', 'feedback' that stores 4 lines in the file above respectively.

{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12 ', 'feedback': 'I want to say thank you to all of you.'}

Thank you so much

Given file.txt where the file is and the format is the one described on the question this would be the code:

path = r"./file.txt"

content = open(path, "r").read().replace("\"", "")
lines = content.split("\n")

dict_ = {
    'title': lines[0],
    'name': lines[1],
    'date': lines[2],
    'feedback': lines[3]
}
print(dict_)

You can basically define a list of keys and match them with lines.

Example:

key_list = ["title","name","date","feedback"]
text = [line.replace("\n","").replace("\"","")  for line in open("text.txt","r").readlines()]
dictionary = {}
for index in range(len(text)):
    dictionary[key_list[index]] = text[index]

print(dictionary)

Output:

{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12', 'feedback': 'I want to say thank you to all of you.'}

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