从文件加载时,将存储为字典的值打印在列表中

时间:2019-02-22 23:45:37

标签: python

我正在加载文本文件并尝试显示其数据。数据采用包含多个字典值的列表形式,例如:

[{"name": "Oliver", "author": "Twist", "read": false}, {"name": "Harry", "author": "Potter", "read": true}, {"name": "Saitao", "author": "Apratim", "read": false}]

我的读取功能定义如下:

def show_all_books():
    with open('data.txt','r') as f:
        books_list = f.read()
        print(books_list)
        if books_list == []:
            print('No books in the database!')
        else:
            for book in books_list:
                read = 'Yes' if book['read'] else 'No'
                print("The book {} authored by {} has been read?: {}".format(book['name'],book['author'],book['read']))

我得到的错误如下:

    read = 'Yes' if book['read'] else 'No'
TypeError: string indices must be integers

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如Robin Zigmond所建议,您可以将字符串转换为对象。

import json

def show_all_books():
    with open('data.txt','r') as f:
        books_list = f.read()
        books = json.loads(books_list)
        if books == []:
            print('No books in the database!')
        else:
            for book in books:
                if book['read']:
                    read = 'Yes'
                else:
                    read = 'No'
                print("The book {} authored by {} has been read?: {}".format(book['name'],book['author'], read))

show_all_books()

然后您得到:

The book Oliver authored by Twist has been read?: No
The book Harry authored by Potter has been read?: Yes
The book Saitao authored by Apratim has been read?: No

希望这会有所帮助