I am a newbie in Python and would like to read a text file into a dictionary. The problem is that it reads in everything and only keeps the last record. I want to read in all the data and store everything in a Python dict
.
It is just a simple text file reading and python data dictionary storing. Not sure why it does not work. Appreciate if someone can help.
book_data = {}
with open('test_data.txt', 'r', encoding='utf8') as raw_data:
for item in raw_data:
if ':' in item:
key,value = item.split(':', 1)
book_data[key]=value.lower()
test_data.txt
Book_ID: #111
Book_Title: Python 101
Book_description: This is a book about Python for beginners.
Book_ID: #222
Book_Title: Java 101
Book_description: This is a book about Java for beginners.
Book_ID: #333
Book_Title: Ruby 101
Book_description: This is a book about Ruby for beginners.
Book_ID: #444
Book_Title: C# 101
Book_description: This is a book about C# for beginners.
My output is just one record instead of 4 records.
for k,v in book_data.items():
print(k," : ", v)
Output:
Book_ID : #444
Book_Title : c# 101
Book_description : this is a book about c# for beginners.