简体   繁体   English

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

[英]Printing values stored as dictionary in a list while loading from a file

I am loading a text file and trying to display its data. 我正在加载一个文本文件并尝试显示其数据。 The data is in a form of list containing multiple dictionary values such as: 数据采用包含多个字典值的列表形式,例如:

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

My read function is defined as follows: 我的读取功能定义如下:

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']))

And the error I get is the following: 我得到的错误如下:

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

Any suggestions? 有什么建议么?

As Robin Zigmond suggested, you could convert the string into an object. 正如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()

Then you get this: 然后你得到这个:

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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM