-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