Dictionaries

A dictionary is a collection data type in Python used to store data in key-value pairs.
Dictionaries are ordered (Python 3.7+), mutable, and do not allow duplicate keys.

They are useful for storing related information together.

CREATING A DICTIONARY

Dictionaries are created using curly brackets { } with key-value pairs separated by colons :.

student = {
"name": "Hira",
"age": 25,
"course": "Python"
}

ACCESSING VALUES

You can access dictionary values using their keys.

print(student["name"])

Using the get() method:

print(student.get("age"))

ADDING OR UPDATING ITEMS

You can add a new key-value pair or update an existing one.

student["city"] = "Karachi"
student["age"] = 26

REMOVING ITEMS

pop() – Removes item by key

student.pop("course")

popitem() – Removes last inserted item

student.popitem()

del – Deletes specific key

del student["city"]

clear() – Removes all items

student.clear()

LOOPING THROUGH A DICTIONARY

Loop through keys

for key in student:
print(key)

Loop through values

for value in student.values():
print(value)

Loop through key-value pairs

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

DICTIONARY METHODS

print(student.keys())
print(student.values())
print(student.items())

NESTED DICTIONARY

A dictionary can contain another dictionary.

students = {
"student1": {"name": "Ali", "age": 20},
"student2": {"name": "Sara", "age": 22}
}print(students["student1"]["name"])

IMPORTANT RULES

• Keys must be unique
• Keys must be immutable (string, number, tuple)
• Values can be any data type
• Dictionaries are mutable

WHEN TO USE DICTIONARIES

• When storing related data
• When mapping one value to another
• For structured data like records, JSON, APIs
• When fast key-based lookup is needed

Understanding dictionaries is essential for handling structured and real-world data in Python programs.

Home » PYTHON INTERMEDIATE (PYI) > Data Structures > Dictionaries