将文本文件解析为字典

时间:2015-02-10 16:13:55

标签: python dictionary

我有一个类似于以下内容的文件:

Book
Key: Norris2013
Author: Elizabeth Norris
Title: Unbreakable
Publisher: Harper Collins Publishers
Date: 2013
Book
Key: Rowling1997
Author: J.K. Rowling
Title: Harry Potter and the Philosopher's Stone
Publisher: Bloomsbury Publishing
Date: 1997
Book
Key: Dickens1894
Author: Charles Dickens
Title: A tale of two cities
Publisher: Dodd, Mead
编辑:我正在将数据输入字典:

newDict = {}

with open('file.txt', 'r') as f:
    for line in f:
        splitLine = line.split()
        newDict[splitLine[0]] = " ".join(splitLine[1:])
print (newDict)

为什么只打印字典的最后一个条目?

1 个答案:

答案 0 :(得分:0)

您一次又一次地覆盖字典,因为您多次重复使用相同的密钥。您可能想要创建一个词典列表:

books = []    # Start with an empty list
book = {}     # and an empty dictionary for the current book
with open('file.txt', 'r') as f:
    for line in f:
        if line.strip() == "Book":  # Are we at the start of a new book? Then...
            if book:                # Add the current book (if there is one) to list
                books.append(book)
                book = {}           # Start a new book
        else:
            splitLine = line.strip().split()
            book[splitLine[0]] = " ".join(splitLine[1:])
if book:                            # Add final book to list
    books.append(book)
print (books)