yerdeth
yerdeth

Reputation: 51

Why does using list(dict_keys()) here, return an empty list?

I am trying to make a Class to represent a Library with a nested class to represent the individual books.

class Library:
    class Book:
        book_data = {}
        def __init__(self, title, year, isbn, author):
            self.title = title
            self.year = year
            self.isbn = isbn
            self.author = author
            Library.Book.book_data[title]={'Date Published':year,'ISBN':isbn,'Auhthor':author}
    
    def __init__(self, username):
        self.username = username
        self.borrowed_books = []

    def checkout_book(self, book_name):
        pass

    def return_book(self, book_name):
        pass

    available_books = Book.book_data.keys() 

When I print out Library.available_books I get the expected result: dict_keys(['Book1','Book2'])

However when I try to convert dict_keys to list by doing so: available_books = list(Book.book_data.keys())

Printing Library.available_books gives me an empty list. Is there a reason why python is converting the keys into an empty list?

Upvotes: 0

Views: 97

Answers (1)

Unmitigated
Unmitigated

Reputation: 89384

available_books = Book.book_data.keys() is run only once, when the dict is empty. Its value will not change each time it is accessed. dict.keys() returns a view of the keys, so you can see modifications after changing the underlying dict, but converting to a list only captures the keys (of which there are none) at the moment available_books is initialized.

Upvotes: 4

Related Questions