Skip to main content

Ex 7: Customer Dictionary

Problem

We need to manage customer data using a Python dictionary. Follow a sequence of steps to create, modify, and query a customer record.

Rules

  1. Create a dictionary named customer with: name ("John Doe"), age (32), and city ("New York").
  2. Add email ("john@johndoe.me") and phone (9836997456) using .update().
  3. Print the customer's name and city.
  4. Check if the key "email" exists in the dictionary.
  5. Remove the "age" field using .pop().
  6. Print all keys, values, and items.
  7. Remove and print the last inserted item using .popitem().
  8. Access the key "membership" safely using .get(), providing "no membership" as a default.
  9. Update the dictionary to include an "address" ("221B Baker Street").
  10. Print the final dictionary state.

Boilerplate

Copy below code and paste to our IDE for head start.

# Write our code inside this function
def manage_customer():
pass # remove this

# Call with test data
manage_customer()

Expected Output

John Doe
New York
True
dict_keys(['name', 'city', 'email', 'phone'])
dict_values(['John Doe', 'New York', 'john@johndoe.me', 9836997456])
dict_items([('name', 'John Doe'), ('city', 'New York'), ('email', 'john@johndoe.me'), ('phone', 9836997456)])
('phone', 9836997456)
no membership
{'name': 'John Doe', 'city': 'New York', 'email': 'john@johndoe.me', 'address': '221B Baker Street'}

Solution

Only view the solution after trying our best.

Show solution
def manage_customer():
# Step 1: Create a customer dictionary
customer: dict[str, str | int] = {"name": "John Doe", "age": 32, "city": "New York"}

# Step 2: Add email and phone
customer.update({"email": "john@johndoe.me", "phone": 9836997456})

# Step 3: Access values
print(customer["name"])
print(customer["city"])

# Step 4: Membership check
print("email" in customer)

# Step 5: Remove a field
customer.pop("age")

# Step 6: View keys, values, and items
print(customer.keys())
print(customer.values())
print(customer.items())

# Step 7: Remove last item
print(customer.popitem())

# Step 8: Safe access with default
print(customer.get("membership", "no membership"))

# Step 9: Final update
customer.update({"address": "221B Baker Street"})

# Step 10: Final state
print(customer)

# Run the function
manage_customer()

Details

Using .get() is much safer than direct indexing because it won't crash if the key is missing. It's a standard Python pattern to use .get() with a default value to provide a fallback without needing extra if checks.