在嵌套字典中添加项目

时间:2020-05-16 18:49:15

标签: python nested

我正在自学Python,并尝试在Python中创建订购应用程序。该程序将用户提供的产品编号及其价格添加到新词典中。

但是我想不出一种将这些物品的价格加在一起的方法。

alijst = {}
kera = {1001 : {"naam" : '60 X 60 Lokeren', 'prijs' : 31.95},#the third item (31.95) is the prize and needs to be used in a calculation later
          1002 : {"naam" : '40 X 80 Houtlook' , 'prijs' : 32.5},
          1003 : {"naam" : '60 X 60 Beïge', 'prijs' :  29.95}}

# The below is for finding the code linked to a product
def keramisch():
    global kera
    global alijst
    klaar = False
    while klaar != True:
        product = int(input("type a product code or press 0 to close: "))
        if product in kera:
            alijst[product] = kera[product]
        else:
            if product == 0:
                klaar = True
# The below is what I tried for calculation (it sucks)
def berekenprijs():
    global alijst
    global prijslijst
    for i, prijs in alijst:
        print(i)
        aantal = int(input("give an ammount"))
        totaalprijs = aantal * prijs
        prijslijst[totaalprijs]
watbestellen()
berekenprijs()

如何将价格纳入最后定义?

2 个答案:

答案 0 :(得分:5)

我认为您的错误在这里:

for i, prijs in alijst:

这将为您提供订单代码(i)和产品,而不是价格。然后该产品具有属性列表,其中一个是“ naam”,另一个是“ prijs”。

还要注意,您需要.items()来遍历键和值。

for i, prijs in alijst.items():

因此,要访问产品名称,您需要输入

print(prijs["naam"])

要获取价格,您需要

print(prijs["prijs"])

后者明显表明此处的命名有误。

因此,我建议将这些变量重命名为

for productcode, product in alijst.items():

,然后使用

访问产品的属性
print(product["naam"])
print(product["prijs"])

还有一些问题,我留给您练习,例如

  • global prijslijst是指未定义的变量
  • 未定义
  • watbestellen()。您可能是用keramisch()代替的
  • prijslijst[totaalprijs]什么也不做,但是由于缺少prijslijst,我很难弄清您想做什么

答案 1 :(得分:0)

尝试以下方法。

我试图尽可能地保留您的代码,但是在我认为它更干净的地方进行了重新组织。

注意:不鼓励使用全局变量,除非出于特殊目的,例如编码游戏,在这种情况下不需要。

def keramisch():
  " Gets product code and verifies that it exists in kera "
  while True:
    product = input('Product code or blank line to close: ')
    if not product:
      return None # blank line entered
    elif product.isnumeric():
      product = int(product)  # covert string to int
      if product in kera:
        return product
      else:
        print('Product code does not exist')
    else:
      print('Product code should be numeric, or blank line to close.')

def berekenprijs():
  " Gets list of products and caculates total "
  alijst = {}
  while True:
    # Get product
    product = keramisch()
    if product is None:
      break

    while True:
      # Get Amount
      aantal = input('Amount of product: ')
      if not aantal.isnumeric():
        print('Amount should be numeric')
      else:
        alijst[product] = int(aantal)
        break  # done with entering amount

  # Calculate total
  total = 0
  for product in alijst:
    price = kera[product]['prijs']
    quantity = alijst[product]

    total += quantity*price  # quantity x price

  print(f'Total Price is: {total}')

kera = {1001 : {"naam" : '60 X 60 Lokeren', 'prijs' : 31.95},#the third item (31.95) is the prize and needs to be used in a calculation later
          1002 : {"naam" : '40 X 80 Houtlook' , 'prijs' : 32.5},
          1003 : {"naam" : '60 X 60 Beïge', 'prijs' :  29.95}}

# Usage
berekenprijs()