Module 21: Mastering Dictionaries

Unlock the power of key-value pairs for efficient data handling in Python.

🔑 What are Dictionaries?

Imagine a real dictionary: you look up a word (key) to find its definition (value). Python dictionaries work similarly! They store data as key-value pairs, allowing fast lookups.

They are incredibly useful in AI for storing configurations, feature sets, results, or any data where you need to access values using a unique identifier (the key).

🔭 Exploring Structure

Keys are unique identifiers pointing to their associated values.

📖

Real Dictionary

Word (Key) ➔ Definition (Value)

Contact List

Name (Key) ➔ Phone Number (Value)

Python Dictionary

'name' (Key) ➔ 'Alice' (Value)

# Creating a simple dictionary
student_info = {
    'name': 'Bob',
    'major': 'AI Engineering',
    'id': 12345
}

⚙️ Common Operations

Let's see how to interact with dictionaries.

Get All Keys

Retrieve just the keys from the dictionary.

my_dict.keys()

Get All Values

Retrieve just the values from the dictionary.

my_dict.values()

Get Key-Value Pairs

Retrieve both keys and values together as pairs (tuples).

my_dict.items()

Check if Key Exists

Use the `in` keyword to see if a key is present before trying to access it.

'my_key' in my_dict

Delete an Item

Remove a key-value pair using the `del` statement and the key.

del my_dict['key_to_delete']

🧠 Dictionaries in AI

How these operations help in AI tasks.

Practical Connections:

Data Manipulation: Dictionaries are perfect for storing structured data like model parameters ('learning_rate': 0.01), feature counts, or configuration settings. Iterating (.items()) lets you process these easily.

Algorithms: Checking for keys (in) is vital for tasks like caching results (memoization) or checking visited nodes in graph algorithms. Deleting items (del) helps manage memory or remove processed data.

Let's simulate updating model parameters stored in a dictionary.

model_params = {
  'layer1_neurons': 128,
  'activation': 'ReLU',
  'dropout_rate': 0.2,
  'optimizer': 'Adam' # Configuration for training
}

# Update a parameter
model_params['dropout_rate'] = 0.3 # Modify existing value

# Maybe remove an unused parameter
if 'optimizer' in model_params: # Check before deleting
    del model_params['optimizer'] # Remove the key-value pair

print(model_params)

🧠 Quick Check!

Module 21 Theory Complete!

Excellent work navigating dictionary operations! You're building essential skills for data handling in AI.
Ready to practice? Head to the Practice Zone or take on the Advanced Practice challenge.