简体   繁体   English

如何在 Python 中更新字典中键的值?

[英]How to update the value of a key in a dictionary in 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

 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?我是否错过了代码中的任何逻辑或任何行?

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
d = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})

print(d)打印(d)

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

You are modifying the list book_shop.values()[i] , which is not getting updated in the dictionary.您正在修改列表book_shop.values()[i] ,该列表未在字典中更新。 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.每当您调用values()方法时,它都会为您提供字典中可用的值,在这里您不会修改字典的数据。

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)

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM