Dictionary — Creating, Accessing, Adding, Modifying, Deleting
A dictionary stores data as key-value pairs, enclosed in curly braces {}. Keys must be unique and immutable (str, int, tuple); values can be any type.
Creating a Dictionary
empty = {}
student = {"name": "Riya", "age": 21, "course": "BCA"}
from_pairs = dict([("a", 1), ("b", 2)])
using_kwargs = dict(name="Amit", age=22)
Accessing Values
student = {"name": "Riya", "age": 21}
print(student["name"]) # 'Riya'
# print(student["marks"]) # KeyError: 'marks'
print(student.get("marks")) # None (safe -- no error)
print(student.get("marks", "N/A")) # 'N/A' (custom default)
Adding and Modifying Items
student = {"name": "Riya", "age": 21}
student["course"] = "BCA" # adds a new key
print(student) # {'name': 'Riya', 'age': 21, 'course': 'BCA'}
student["age"] = 22 # modifies an existing key
print(student) # {'name': 'Riya', 'age': 22, 'course': 'BCA'}
Deleting Items
student = {"name": "Riya", "age": 21, "course": "BCA"}
del student["age"] # removes key "age"
print(student) # {'name': 'Riya', 'course': 'BCA'}
removed = student.pop("course") # removes & returns the value
print(removed, student) # 'BCA' {'name': 'Riya'}
student.clear() # empties the dictionary
print(student) # {}
Iterating a Dictionary
student = {"name": "Riya", "age": 21, "course": "BCA"}
for key in student: # keys only
print(key)
for key, value in student.items(): # keys and values
print(key, ":", value)
for value in student.values(): # values only
print(value)
Checking key existence
print("name" in student) # True
print("marks" in student) # False
Nested Dictionary
students = {
"s1": {"name": "Riya", "marks": 92},
"s2": {"name": "Amit", "marks": 78}
}
print(students["s1"]["name"]) # 'Riya'