A Dictionary in Python (programming language) is used to store data in key–value pairs.

Each item in a dictionary has:

  • a key πŸ—οΈ
  • a value πŸ“¦

Example:
{"name": "Rahul", "age": 20}

Here:

  • name β†’ key
  • Rahul β†’ value

Key Features

  • Ordered (from Python 3.7+)
  • Mutable (can change values)
  • Keys must be unique
  • Values can be any data type

1️⃣ Creating a Dictionary

Dictionaries use curly braces {}.

student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}

print(student)

Output

{'name': 'Rahul', 'age': 20, 'course': 'Python'}

2️⃣ Accessing Dictionary Values

Use the key to access values.

student = {
"name": "Rahul",
"age": 20
}

print(student["name"])
print(student["age"])

Output

Rahul
20

3️⃣ Using get() Method

get() is safer because it does not cause an error if the key doesn’t exist.

student = {"name": "Rahul", "age": 20}print(student.get("name"))

4️⃣ Changing Dictionary Values

Values can be modified easily.

student = {
"name": "Rahul",
"age": 20
}

student["age"] = 21

print(student)

Output

{'name': 'Rahul', 'age': 21}

5️⃣ Adding New Items

Add a new key-value pair.

student = {
"name": "Rahul",
"age": 20
}

student["city"] = "Delhi"

print(student)

Output

{'name': 'Rahul', 'age': 20, 'city': 'Delhi'}

6️⃣ Removing Items

pop()

Removes an item using a key.

student = {
"name": "Rahul",
"age": 20
}

student.pop("age")

print(student)

Output

{'name': 'Rahul'}

del

student = {
"name": "Rahul",
"age": 20
}

del student["age"]

print(student)

7️⃣ Dictionary Length

Use len() to count items.

student = {
"name": "Rahul",
"age": 20,
"city": "Delhi"
}

print(len(student))

Output

3

8️⃣ Loop Through a Dictionary

Loop through keys.

student = {
"name": "Rahul",
"age": 20
}

for key in student:
print(key)

Output

name
age

Loop through values.

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

Loop through key-value pairs.

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

9️⃣ Nested Dictionary

A dictionary can contain another dictionary.

students = {
"student1": {"name": "Rahul", "age": 20},
"student2": {"name": "Amit", "age": 21}
}

print(students["student1"]["name"])

Output

Rahul

πŸ”Ÿ Clear a Dictionary

student = {"name": "Rahul", "age": 20}

student.clear()

print(student)

Output

{}

⭐ Summary

FeatureDictionary
StructureKey : Value
OrderedYes
MutableYes
Duplicate KeysNot Allowed

βœ… Example Program

student = {
"name": "Rahul",
"age": 20
}
student["course"] = "Python"for key, value in student.items():
print(key, ":", value)

Output

name : Rahul
age : 20
course : Python