πŸ“˜ Dictionary in Python

πŸ”Ή What is a Dictionary in Python?

A dictionary in Python is a built-in data structure used to store data in key–value pairs. Dictionaries are unordered (insertion-ordered from Python 3.7+), mutable, and do not allow duplicate keys.

πŸ‘‰ Dictionaries are widely used for fast data lookup and structured data storage.

Article Algo

βœ… Why Use Dictionaries?

  • Fast access using keys
  • Store structured and related data
  • Flexible and dynamic size
  • Efficient for lookups and mappings

πŸ“Œ Creating a Dictionary

student = {
  "name": "John",
  "age": 21,
  "course": "Python"
}

πŸ”Έ Empty Dictionary

empty_dict = {}

πŸ“‚ Types of Dictionaries (Common Usage)

1️⃣ Simple Dictionary

marks = {"math": 90, "science": 85}

2️⃣ Mixed Dictionary

data = {"id": 101, "active": True, "score": 9.5}

3️⃣ Nested Dictionary

employee = {
  "name": "Alice",
  "details": {"age": 30, "dept": "IT"}
}

πŸ“Œ Accessing Dictionary Elements

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

βœ” get() avoids errors if the key is missing.

πŸ“Œ Modifying a Dictionary

Dictionaries are mutable.

student["age"] = 22
student["city"] = "New York"

πŸ“Œ Removing Elements

student.pop("city")
del student["course"]
student.clear()

πŸ“š Dictionary Methods

Method Description
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
update() Updates dictionary
pop() Removes a key
clear() Removes all items
student.keys()
student.values()
student.items()

πŸ“Œ Looping Through a Dictionary

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

πŸ“Œ Dictionary Comprehension

Create dictionaries in a single line.

squares = {x: x*x for x in range(1, 6)}

πŸ“Œ Checking Keys and Values

"name" in student
21 in student.values()

πŸ“Œ Copying a Dictionary

new_student = student.copy()

βœ… Advantages of Dictionaries

  • Fast data access
  • Flexible and dynamic
  • Easy to store structured data
  • Highly efficient for lookups

❌ Disadvantages of Dictionaries

  • Uses more memory
  • Keys must be immutable
  • No direct indexing

πŸ“Š Dictionary vs List (Quick Comparison)

Feature Dictionary List
Storage Key–Value Index-based
Access Speed Faster Slower
Mutability Mutable Mutable

🌍 Real-World Use Cases

  • Storing user profiles
  • Database records
  • Configuration settings
  • JSON data handling
  • API responses