Day 18: Dictionary Operations

Start with a dict of fruits and prices. Add an item, update a price, delete one, and loop to print all items. (Concepts: .update(), .pop(), looping over dicts)

fruits = {"apple": 1.0, "banana": 0.5}
print("Original:", fruits)
fruits["orange"] = 0.8  # Add
fruits["apple"] = 1.2   # Update
fruits.pop("banana")    # Delete
print("Modified:", fruits)

for fruit, price in fruits.items():
    print(fruit, "costs $", price)

Students, Day 18: Manipulate dicts! Start fruits = {"apple": 1.0, "banana": 0.5}. Add: fruits["orange"] = 0.8—new key or updates if exists. Update: fruits["apple"] = 1.2. Delete: fruits.pop("banana")—removes key-value pair. Print changes.

Loop: for fruit, price in fruits.items():—.items() gives key-value tuples, unpacks to variables. Print each. Run: Original/modified dicts, then "apple costs $ 1.2", "orange costs $ 0.8".

In time, try .keys() for keys only or .values() for values. Dicts for dynamic data like inventories—mutable like lists but keyed. Building on Day 17!

Key Concepts:

  • Adding/Updating: Assign to a new/existing key (e.g., dict["key"] = value).
  • .pop(key): Removes and returns the value for the given key.
  • Looping Over Dicts: Use .items() to iterate key-value pairs (e.g., for k, v in dict.items():).

1 thought on “Day 18: Dictionary Operations”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top