Python Mastery – From Basics to Brilliance / Data Structures in Python

Dictionaries

A dictionary is an unordered, mutable collection of key-value pairs. Each key is unique and maps to a value.

person = {"name": "Alice", "age": 30}

🔍 Why Use Dictionaries?

  • To store related data as pairs (like name–age, word–meaning, username–password).

  • Allows fast lookups using keys.

  • Flexible and widely used in real-world data structures (like JSON).


📌 Common Dictionary Operations

person["age"] = 31         # ✅ Update existing value
person["city"] = "Delhi"   # ✅ Add new key-value pair
print(person["name"])      # ✅ Access value by key

You can also remove a key:

del person["age"]

🔄 Looping Through a Dictionary

for key, value in person.items():
    print(key, ":", value)
name : Alice
age : 31
city : Delhi

💡 Real-life Analogy

A dictionary is like a real-life dictionary:

You look up a word (key) and get its meaning (value).