-2
我是新来的Python,并且正在努力理解列表解析,所以我可以在我的代码中使用它。编制列表理解,初学者
pricelist = {"jacket":15, "pants":10, "cap":5, "baseball":3, "gum":1}
products_sold = []
while True:
product_name = input("what is the name of the product")
product = {}
customer_name = input("what is the name of the customer")
#customer is shopping
product[sell_price] = pricelist[product_name]
product["quantity"] = input("how many items were sold?")
#append the product to a dict
products_sold.append(product)
现在我想对整个交易的字典看起来应该像这样的:
transaction = {"customer_name":"name",
"sold":{"jacket":3, "pants":2},
"bought":{"cap":4, "baseball":2, "gum":"10"}}
我将如何创建一个字典,并用列表理解为它分配键和值?我已经看过例子,并且我理解它们,但我无法弄清楚如何将它们应用于我的代码。
我的意图是将我的产品列表变成一个以不同方式包含相同信息的字典(交易)列表。
产品是字典吗? `products_sold`最终是一个列表,每个列表中有1个条目? – mikej 2011-01-28 15:47:10