Dictionary Methods
Common Dictionary Methods
Dictionaries have many useful methods for working with key-value pairs. Here are the most commonly used ones:
dict_methods.py
person = {"name": "Alice", "age": 25}
# get() - safely get value with default
age = person.get("age", 0)
city = person.get("city", "Unknown")
# keys() - get all keys
keys = person.keys()
print(list(keys)) # ['name', 'age']
# values() - get all values
values = person.values()
print(list(values)) # ['Alice', 25]
# items() - get all key-value pairs
items = person.items()
print(list(items)) # [('name', 'Alice'), ('age', 25)]
Adding and Removing Items
Methods for modifying dictionary contents:
modifying.py
person = {"name": "Alice"}
# update() - add or update multiple items
person.update({"age": 25, "city": "NYC"})
# pop() - remove and return value
age = person.pop("age")
print(age) # 25
# popitem() - remove and return last item
item = person.popitem()
print(item) # ('city', 'NYC')
# clear() - remove all items
person.clear()
print(person) # {}
Dictionary Operations
Useful operations for working with dictionaries:
operations.py
dict1 = {"a": 1, "b": 2}
# copy() - create shallow copy
dict2 = dict1.copy()
# Check if key exists
if "a" in dict1:
print("Key 'a' exists")
# Get length
print(len(dict1)) # 2
# setdefault() - get value or set default
value = dict1.setdefault("c", 3)
print(dict1) # {'a': 1, 'b': 2, 'c': 3}
Best Practices
✅ Dictionary Usage Tips
• Use get() instead of direct access to avoid KeyError
• Use in to check if key exists before accessing
• Use items() to iterate over key-value pairs
• Use update() to merge dictionaries
• Dictionary keys must be immutable (strings, numbers, tuples)
main.py
📤 Output
Click "Run" to execute...