Python Dictionaries


dictionary is a collection of key-value pairs.
It is unordered, changeable, and indexed.


🔹 Create a Dictionary

student = {
    "name": "John",
    "age": 22,
    "course": "Python"
}
print(student)

🔹 Access Items

print(student["name"])         # John
print(student.get("age"))      # 22

🔹 Change Values

student["age"] = 23

🔹 Loop Through Dictionary

for key in student:
    print(key, student[key])

Or use:

for key, value in student.items():
    print(key, value)

🔹 Check If Key Exists

if "name" in student:
    print("Yes")

🔹 Dictionary Length

print(len(student))  # 3

🔹 Add Items

student["grade"] = "A"

🔹 Remove Items

student.pop("course")
del student["age"]
student.clear()  # Removes all items

🔹 Copy Dictionary

new_dict = student.copy()

🔹 Nested Dictionaries

students = {
    "student1": {"name": "John", "age": 22},
    "student2": {"name": "Alice", "age": 21}
}

🧪 Try It Yourself

Create a dictionary, update values, loop through items, and practice nested structures.


Practice Questions

Q1. Write a Python program to create a dictionary with keys: "name", "age", and "city".

Q2. Write a Python program to access and print the value of "age" from the dictionary.

Q3. Write a Python program to change the value of "city" to "Delhi".

Q4. Write a Python program to add a new key "country" with the value "India" to the dictionary.

Q5. Write a Python program to remove the key "age" from the dictionary using pop() or del.

Q6. Write a Python program to check if the key "name" exists in the dictionary.

Q7. Write a Python program to print all key-value pairs in the dictionary using a for loop.

Q8. Write a Python program to copy one dictionary into another using the copy() method.

Q9. Write a Python program to create a dictionary with 3 student records, where each student is stored as a nested dictionary.

Q10. Write a Python program to clear all items from a dictionary using the clear() method.


Go Back Top