I have a dictionary which represents a book shop. The keys represent the book title and values represent the number of copies of the book present. When books are sold from the shop, the number of copies of the book must decrease.
I have written a code for decreasing the number of copies of the sold book, but on printing the dictionary after the update, I get the initial dictionary and not the updated one.
n = input("Enter number of books in shop: ") book_shop = {} # Creating a dictionary book_shop # Entering elements into the dictionary for i in range(n): book_title = raw_input("Enter book title: ") book_no = input("Enter no of copies: ") book_shop[book_title] = book_no choice = raw_input("Do you want to sell?") if (choice in 'yesYES'): for i in range(n): print("Which book do you want to sell: ", book_shop) ch1 = raw_input("Enter your choice: ") if(book_shop.keys()[i] == ch1): book_shop.keys()[i] = (book_shop.values()[i]-1) break print(book_shop)
I would like to solve the problem in the simplest way possible. Have I missed any logic or any line in the code?
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {} >>> books['book'] = 3 >>> books['book'] -= 1 >>> books {'book': 2}
In your case:
book_shop[ch1] -= 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With