-1

修改您为上一个任务编写的函数,使其返回字典字典,而不是字典列表。字典应该是这样的

{ 
   1: {'Product': 'Milk', 'Brand': 'Anchor', 'Cost': '4.90'},   
   2: {'Product': 'Bread', 'Brand': 'Vogel', 'Cost': '3.80'} 
}

这是我的代码。

def run():
    dic_keys = ['Product', 'Brand', 'Cost']
    products = {}

    is_quit = False
    while not is_quit:
    product = {}
    for key in dic_keys:
        name = input("Enter {}: ".format(key))
        if name == 'quit':
            return products

        product[key] = name
    products.append(product)  <<--- Do I need to append the product(dictionary) to the 
                                    products(dictionary outside while loop?

print(run())

以前,结果应如下所示:

[{'Product': 'Milk', 'Brand': 'Anchor', 'Cost': '4.90'},
 {'Product': 'Bread', 'Brand': 'Vogel', 'Cost': '3.80'}]

现在应该是这样的:

{ 1: {'Product': 'Milk', 'Brand': 'Anchor', 'Cost': '4.90'},
  2: {'Product': 'Bread', 'Brand': 'Vogel', 'Cost': '3.80'} }

字典的字典,而不是列表的字典。

4

1 回答 1

0

您不能将值附加到字典中。要将值分配给字典,您需要像这样解析字典的键:

products = {}
product = {'Product': 'Milk', 'Brand': 'Anchor', 'Cost': 4.90\
products[1] = product

现在您可以通过 products[1] 访问数组产品中的值,因为 1 是值的键。

我对你的问题的方法是这样的:

def run():
   dic_keys = ['Product', 'Brand', 'Cost']
   dic_id = 1
   products = {}
   is_quit = False

   while not is_quit:
      product = {}
      for key in dic_keys:
         val = input("Enter {}: ".format(key))
         if val == "quit":
            is_quit = True
            break
         product[key] = val

      if len(product) == 3:
         products[dic_id] = product
      dic_id += 1

   return products

print(run())
于 2020-06-07T09:15:17.550 回答