#๐ adding a nested dictionary
8 messages ยท Page 1 of 1 (latest)
@latent dirge
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
class Book:
def __init__(self, title, author, isbn, year):
self.bookshelves = {}
self.books = []
self.title = title
self.author = author
self.isbn = isbn
self.year = year
def add_books(self):
self.bookshelves[self.title] = {}
self.bookshelves[self.title]['Author'] = self.author
self.bookshelves[self.title]['isbn'] = self.isbn
self.bookshelves[self.title]['year'] = self.year
print(self.bookshelves)
def show_case(self):
book_list = []
for key in self.bookshelves:
book_list.append(key)
print(book_list)
book_1 = Book('Mistborn', 'Brandon Sanderson', '9780765360960', '2006')
book_1.add_books()
book_2 = Book('Shadow Slave', 'Guiltythree', 'B0B7MJH9TK', '2022/2023')
book_2.add_books()
book_1.show_case()
book_2.show_case()
output :
{'Mistborn': {'Author': 'Brandon Sanderson', 'isbn': '9780765360960', 'year': '2006'}}
{'Shadow Slave': {'Author': 'Guiltythree', 'isbn': 'B0B7MJH9TK', 'year': '2022/2023'}}
['Mistborn']
['Shadow Slave']
I need the output to be
output:
{'Mistborn': {'Author': 'Brandon Sanderson', 'isbn': '9780765360960', 'year': '2006'},
{'Shadow Slave': {'Author': 'Guiltythree', 'isbn': 'B0B7MJH9TK', 'year': '2022/2023'}}
['Mistborn','Shadow Slave']
How do I not create a new dictionary every time I add a new title?
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.