簡體   English   中英

將 int 添加到 Python 字典現有鍵而不覆蓋所述鍵

[英]Add int to Python dictionary existing key without overwriting said key

我想知道是否有一種方法可以解決我嘗試將用戶輸入“int”添加到同一個字典而不覆蓋以前的輸入而不是添加到它的地方。

這是主字典和空白字典

Packaged_goods={1:{'item':'Bread','price':1.45,'gst':0.10,'offer':'No'},

shopping_basket={}

我在提到的字典中選擇項目的功能

def package_select():
    sort=int(input('How do you want to sort your category by?\n'
                   '1.By name.\n'
                   '2.Ascending in price.\n'
                   '3.Descending in price.\n'
                   '4.Return previous menu\n'
                   'enter your input: '))
    if sort==1:
        res = sorted(Packaged_goods.items(), key = lambda x: x[1]['item'])
        print(*res, sep = "\n")
        choose=(int(input('4.Exit back to menu\n'
                          'Enter your option(1-4): ')))
        # choose=int(input("Sorted by name: " + str(res)))

在這里,我將輸入我想要的項目數量。

    if choose 1:
        qnty=int(input('How many do you want?: '))
        price=(Packaged_goods[choose]['price'])
        y = ((Packaged_goods[choose]['price']) * qnty)
        gst = (Packaged_goods[choose]['gst'])
        offer = (Packaged_goods[choose]['offer'])
        if choose==1:
            if 'Bread' not in shopping_basket.keys():
             shopping_basket['Bread'] ={'Quantity': qnty, 'Individual price': price, 'total': y, 'GST': gst, 'offer': offer}
            else:
                shopping_basket['Bread']['Quantity'].append(qnty) 

假設我輸入了 3 個面包,我的輸出將是

Bread , {'Quantity': 3, 'Individual price': 1.45, 'total': 4.35, 'GST': 0.1, 'offer': 'No'}

現在我再次運行程序,我想再添加 2 個面包,我想要的結果是

#desired outcome
    Bread , {'Quantity': 5, 'Individual price': 1.45, 'total': 4.35, 'GST': 0.1, 'offer': 'No'}

但相反,它會給我新整數的“數量”值。

#actual outcome
    Bread , {'Quantity': 2, 'Individual price': 1.45, 'total': 4.35, 'GST': 0.1, 'offer': 'No'}

我如何解決這個增加價值的問題? 謝謝

當我運行它時編輯*下面的代碼

            if choose==1:
            if 'Bread' not in shopping_basket.keys():
             shopping_basket['Bread'] ={'Quantity': qnty, 'Individual price': price, 'total': y, 'GST': gst, 'offer': offer}
            else:
                shopping_basket['Bread']['Quantity'].append(qnty)

會給我一個錯誤

AttributeError: 'int' object has no attribute 'append'

考慮更改以下行:

shopping_basket['Bread']['Quantity'].append(qnty)

shopping_basket['Bread']['Quantity'] += qnty

在前者中,您只需將值更改為新的 qnty。 稍后,數量會根據需要更新:)

這是因為您在下面的代碼段中對int值使用了append

shopping_basket['Bread']['Quantity'].append(qnty) 

相反,你應該使用這個:

shopping_basket['Bread']['Quantity'] += qnty

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM