I'm new to Python and am trying to understand list comprehensions so I can use it in my code.
pricelist = {"jacket":15, "pants":10, "cap":5, "baseball":3, "gum":1}
products_sold = []
while True:
product_nam开发者_JS百科e = 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)
now I want to have a dict of the entire transaction that should look like this:
transaction = {"customer_name":"name",
"sold":{"jacket":3, "pants":2},
"bought":{"cap":4, "baseball":2, "gum":"10"}}
how would I create a dict, and assign it keys and values with a list comprehension? I've looked at examples, and I understand them, but I can't figure out how to apply them to my code.
My intentions is to turn my list of products into a list of dicts(transaction) which contain the same information in a different way.
I'll answer what I think your real problem which is that you want to understand list comprehensions. IMO, the example that you posted to try to learn list comprehensions is not a good example. Here's a very trivial example I like to use since it should be easy to relate this to what you already know from another language.
# start with a list of numbers
numbers = [1, 2, 3, 4, 5]
# create an empty list to hold the new numbers
numbers_times_two = []
# iterate over the list and append the new list the number times two
for number in numbers:
numbers_times_two.append(number * 2)
Hopefully, the above code makes sense and is familiar to you. Here's the exact same thing using list comprehensions. Notice, all the same parts are there, just moved around a bit.
numbers_times_two = [number * 2 for number in numbers]
List comprehensions use square brackets just like a list and it creates a new list from iterating over an iterable (list-like thing) which is numbers in this example.
So, you can see that when you asked a question about using list comprehension to populate a dict, it really doesn't make sense in the context of learning the mechanics of list comprehensions.
Hope this helps.
精彩评论