How to update the value of a key in a dictionary in Python?

Question:

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?

Asked By: Animeartist

||

Answers:

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
Answered By: Christian W.

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

Answered By: Nikhil Sagotiya
n = eval(input('Num books: '))
books = {}
for i in range(n):
    titlez = input("Enter Title: ")
    copy = eval(input("Num of copies: "))
    books[titlez] = copy

prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
    choice = input('Enter book title: ')
    if choice in books:
        init_num = books[choice]
        init_num -= 1
        books[choice] = init_num
        print(books)
Answered By: vic

You can simply specify another value to the existed key:

t = {}
t['A'] = 1
t['B'] = 5
t['C'] = 2

print(t)

{'A': 1, 'B': 5, 'C': 2}

Now let’s update one of the keys:

t['B'] = 3

print(t)

{'A': 1, 'B': 3, 'C': 2}
Answered By: Aymen Alsaadi
d = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})

print(d)

{'A': 2, 'B': 5, 'C': 2}
Answered By: laplace
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.