如何在Python中更新字典中键的值? [英] How to update the value of a key in a dictionary in Python?

查看:875
本文介绍了如何在Python中更新字典中键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本代表书店的字典.键代表书名,值代表当前书的份数.从商店出售书籍时,书籍的副本数必须减少.

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
 ch=raw_input("Do you want to sell")
 if (ch in 'yesYES'):
        for i in range(n):
             print"which book you want to sell??",book_shop
             ch1=raw_input("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?

推荐答案

好吧,您只需引用键就可以直接从值中减去.我认为哪个更简单.

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}   

在您的情况下:

book_shop[ch1] -= 1

这篇关于如何在Python中更新字典中键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆