Search code examples
pythondictionaryreadfile

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


Solution

  • 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.'}