SwadhyAI Notes

All Python notes

Python Dictionaries 📖

Key-Value Pairs

Dictionaries are used to store data values in key:value pairs. They are ordered (since Python 3.7), changeable, and do not allow duplicates.

📒 Analogy: The Phonebook

A dictionary is like a phonebook (or your contacts app).
- You look up a name (Key) to find their number (Value).
- You can't have two people with the exact same name (Unique Keys).
- Finding a number is instant; you don't have to read every single name from A to Z (Hash Map efficiency).

✨ Creating and Accessing

python
car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

print(car["brand"]) # Ford
print(car.get("model")) # Mustang (Safer method)

🔄 Looping Dictionaries

You can loop through a dictionary by using a for loop.

python
# Loop through keys
for x in car:
  print(x)

# Loop through values
for x in car.values():
  print(x)

# Loop through both keys and values
for key, value in car.items():
  print(f"{key}: {value}")

🎯 Real-World Application: API Responses

Dictionaries are the standard way to handle JSON data from APIs.

python
user_data = {
    "id": 101,
    "username": "johndoe",
    "is_active": True,
    "roles": ["admin", "editor"]
}

if user_data["is_active"]:
    print(f"Welcome back, {user_data['username']}!")

🚀 Dictionary Comprehension

Just like list comprehension, you can create dictionaries using a concise syntax.

python
keys = ['a', 'b', 'c']
values = [1, 2, 3]

my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}

âž• Merging Dictionaries (Python 3.9+)

You can merge two dictionaries using the | operator.

python
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged = dict1 | dict2
print(merged)
# Output: {'a': 1, 'b': 3, 'c': 4} (Note: 'b' is updated)

✨ Pro Tip: Defaultdict

The collections module has a defaultdict which never raises a KeyError. It provides a default value for the key that does not exist.

python
from collections import defaultdict
d = defaultdict(int)

d["a"] = 1
print(d["b"]) # Output: 0 (Default value for int)