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
- Create a dictionary named
customerwith:name("John Doe"),age(32), andcity("New York"). - Add
email("john@johndoe.me") andphone(9836997456) using.update(). - Print the customer's
nameandcity. - Check if the key
"email"exists in the dictionary. - Remove the
"age"field using.pop(). - Print all keys, values, and items.
- Remove and print the last inserted item using
.popitem(). - Access the key
"membership"safely using.get(), providing "no membership" as a default. - Update the dictionary to include an
"address"("221B Baker Street"). - 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.