Dictionaries have methods for accessing and modifying key-value pairs.
Getting values
person = {"name": "Alex", "age": 25}
print(person.get("name")) # Alex
print(person.get("city")) # None (no error)
print(person.get("city", "Unknown")) # Unknown
Adding or updating
person["city"] = "Berlin" # Add new
person["age"] = 26 # Update existing
Update multiple:
person.update({"job": "developer", "age": 27})
print(person)
Removing items
age = person.pop("age") # Removes and returns value
print(age) # 27
person.popitem() # Removes last item
del person["job"] # Delete by key
person.clear() # Empty dictionary
Checking keys
print("name" in person) # True or False
print(person.keys()) # dict_keys(['name', 'city'])
print(person.values()) # dict_values(['Alex', 'Berlin'])
print(person.items()) # dict_items([('name', 'Alex'), ...])
Simple examples
Student grades:
grades = {"math": 90, "science": 85}
grades["english"] = 88
print(grades.get("math")) # 90
Config settings:
settings = {"theme": "dark"}
settings.update({"font": "large", "notifications": True})
print(settings)
Quick summary
- Get safely with
.get(). - Add/update with assignment or
.update(). - Remove with
.pop(),.popitem(),del,.clear(). - View with
.keys(),.values(),.items().
Practice dictionary methods on data. They are essential for managing key-value information in Python programs.
Top comments (0)