Dictionary Discount Example Help

In the Dictionary Theory section called “What Are Some Common Techniques to Loop Over a Dictionary?”, it gets to the code example where it uses the Loop function to implement the discounts.

I’m just not understanding what it’s doing there, why it’s recalling the Dictionary variable in the line and then putting the ‘product’ variable in the brackets like that.

products[product] = round(price * 0.8)

It’s hard sometimes in Freecodecode camp when it just shows an example but doesn’t explain WHY the pieces and variables are used in those spots. Any help is appreciated.

Welcome to the forum @Hikaru

Here is the text for the discount section.

Now that you know more about this, we can go back to our initial example. If we want to offer a 20% discount, we would multiply each price by 0.8 and reassign it as the value of that product key.

We could also round the result down if we want to work with integers:

products = {
    'Laptop': 990,
    'Smartphone': 600,
    'Tablet': 250,
    'Headphones': 70,
}

for product, price in products.items():
    products[product] = round(price * 0.8)

print(products)
#{'Laptop': 792, 'Smartphone': 480, 'Tablet': 200, 'Headphones': 56}

The most important part before proceeding with this lesson is understanding the various methods:

The .values(), .keys(), and .items() methods are essential for these techniques. We covered them briefly in a previous lesson.

products.items() generates a list of tuples.

print(products.items())
# dict_items([('Laptop', 990), ('Smartphone', 600), ('Tablet', 250), ('Headphones', 70)])

The for loop iterates over each tuple in the list. In the first iteration, the product variable refers to the “Laptop” string, the price variable refers to the number 990.

    products["Laptop"] = round(990 * 0.8)

The above assignment applies a discount of 80% to the value of the laptop, in the products dictionary.

Happy coding

product is the variable that holds the current dictionary key (like "apple" or "banana") during each loop iteration. So products[product] means “access the value for this specific key in the dictionary.” The line products[product] = round(price * 0.8) calculates the discounted price and stores it back into the dictionary for that product.