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

时间:2016-12-09 15:28:17

标签: python dictionary

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

我已经编写了一个代码来减少销售图书的副本数量,但是在更新后打印字典时,我得到的是初始字典,而不是更新的字典。

 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

我想以最简单的方式解决问题。我错过了代码中的任何逻辑或任何一行吗?

5 个答案:

答案 0 :(得分:24)

您可以通过引用密钥直接从值中减去。在我看来哪个更简单。

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

在你的情况下:

book_shop[ch1] -= 1

答案 1 :(得分:3)

d = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})

打印(d)

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

答案 2 :(得分:0)

您正在修改列表public class CassandraTest{ @Autowired private CassandraOperations cassandraTemplate; public void execute() { Select sel = QueryBuilder.select("max(id)").from("table").; Integer maxId= cassandraTemplate.queryForObject(sel, Integer.class); System.out.println("maxid ===> " + maxId); } } ,该列表未在字典中更新。无论何时调用$data = mysqli_query($conn,$query) or die(mysqli_error($conn)); if($data) { echo '<script type="text/javascript">'; echo 'alert("YOUR REGISTRATION IS COMPLETED...")'; echo '</script>'; echo '<script type="text/javascript">'; echo 'setTimeout(function() {'; echo 'window.location.href = "http://stackoverflow.com"'; echo '}, 5000); // <-- redirect after 5 seconds'; echo '</script>'; } 方法,它都会为您提供字典中可用的值,而这里您不会修改字典的数据。

答案 3 :(得分:0)

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)

答案 4 :(得分:0)

您可以简单地为现有键指定另一个值:

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

print(t)

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

现在让我们更新其中一个键:

t['B'] = 3

print(t)

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