Advertisement
Beginner Python, Data Types & Structures

How do you access, add, and remove items from a dictionary?

Short answer

Access a value with dict[key] (raises KeyError if missing) or dict.get(key, default) (returns None or a default instead); add/update with dict[key] = value; remove with del dict[key] or dict.pop(key), the latter also returning the removed value.

Save Python mock interview
Advertisement
AModel answer
Access a value with dict[key] (raises KeyError if missing) or dict.get(key, default) (returns None or a default instead); add/update with dict[key] = value; remove with del dict[key] or dict.pop(key), the latter also returning the removed value.
person = {"name": "Sam", "age": 30}
print(person["name"])          # 'Sam'
person["city"] = "NYC"          # add a new key
age = person.pop("age")         # remove and return 30
print(person.get("email", "N/A"))  # 'N/A' -- safe default lookup
Real-world example
Storing and updating a user's profile information as key-value pairs, safely handling missing fields.
Likely follow-ups
  • What's the difference in behavior between dict[missing_key] and dict.get(missing_key)?
Related topics