python 如何在用户添加条目时自动分配一个新数字作为字典中的键?

46scxncf  于 2023-02-07  发布在  Python
关注(0)|答案(1)|浏览(87)

例如,我有一个空字典称为购物清单。它应该存储键,如#“1,2,3,4 ...”和值应该是一个列表,存储项目的名称和价格。由于某种#原因,我只能有1键在购物清单中只有...

代码如下:

便利店的产品目录,包括代码编号、项目名称、价格和库存量。

items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk 
 tea',500,0]}
 shopping_list = {}

 query = input("Enter the code number of the item you want to get: ")
 query = int(query)
 for i in items:
     if query == i:
          item = i
          print(items[item][0], "will cost you", "{:.2f}".format(items[item][1]/100),"dollars")
    
 #Temporary shopping list shall store item code, name and price from original list of product
 n=0
 buy_more = input("Do you wish to choose some more items? (Y or N) ")
 while buy_more.isdigit() and buy_more not in "Yy" and buy_more not in "Nn":
       print("Please enter (Y or N) only. ")
       buy_more = input("Do you wish to choose some more items? (Y or N) ")

       #loopback and let users to buy an additional item
       while buy_more in "Yy":
            shopping_list[n] = [items[item][0],items[item][1]]
            print("Nice! Please choose one more item.")
            buy_more = input("Do you wish to choose some more items? (Y or N) ")

       #Continue to the transaction process
       if buy_more in "Nn":
            print("Continue to transaction process. ")
            break
shopping_list[n] = [items[item][0],items[item][1]]
print(shopping_list).   `
yzxexxkh

yzxexxkh1#

我优化了你的代码一点,也许它会有所帮助,在这里的代码,因为你要求输入的项目代码,我不增加它:

items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk tea',500,0]}
shopping_list = {}

#Temporary shopping list shall store item code, name and price from original list of product
buy_more='y'
while buy_more:
    if buy_more not in 'YyNn': 
        print("Please enter (Y or N) only. ")
        buy_more = input("Do you wish to choose some more items? (Y or N) ")

   #loopback and let users to buy an additional item
    while buy_more in "Yy":
        query = int(input("Enter the code number of the item you want to get: "))
        print(items[query][0], "will cost you", "{:.2f}".format(items[query][1]/100),"dollars")
        shopping_list[query] = [items[query][0],items[query][1]]
        print("Nice! Please choose one more item.")
        buy_more = input("Do you wish to choose some more items? (Y or N) ")

        #Continue to the transaction process
    if buy_more in "Nn":
        print("Continue to transaction process. ")
        break
        
print(shopping_list)

相关问题