Chapter 6: Data Structures / Lesson 36

Dictionaries

Introduction to Dictionaries

Dictionaries are Python's implementation of associative arrays or hash tables. They store data as key-value pairs, making it easy to look up values by their keys. Dictionaries are unordered (in Python 3.6 and earlier), mutable, and don't allow duplicate keys.

Dictionaries are perfect for storing structured data like user information, configuration settings, or any data where you need to associate values with unique identifiers.

Creating Dictionaries

Dictionaries are created using curly braces {} with key-value pairs separated by colons:

creating_dicts.py
# Empty dictionary empty = {} # Dictionary with key-value pairs person = { "name": "Alice", "age": 25, "city": "New York" } # Using dict() constructor scores = dict(math=95, science=87, english=92) print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'} print(scores) # {'math': 95, 'science': 87, 'english': 92}

Accessing Values

Access dictionary values using square brackets with the key, or use the get() method:

accessing_dicts.py
person = {"name": "Alice", "age": 25} # Access by key print(person["name"]) # Alice print(person["age"]) # 25 # Using get() method (safer) print(person.get("name")) # Alice print(person.get("city", "Unknown")) # Unknown (default value) # Check if key exists if "age" in person: print("Age exists!")

Modifying Dictionaries

Dictionaries are mutable, so you can add, update, or remove items:

modifying_dicts.py
person = {"name": "Alice", "age": 25} # Add new key-value pair person["city"] = "New York" # Update existing value person["age"] = 26 # Remove item del person["city"] print(person) # {'name': 'Alice', 'age': 26}

Iterating Over Dictionaries

You can loop through dictionaries in several ways:

iterating_dicts.py
person = {"name": "Alice", "age": 25, "city": "NYC"} # Loop through keys for key in person: print(key, person[key]) # Loop through items (key-value pairs) for key, value in person.items(): print(f"{key}: {value}") # Loop through values only for value in person.values(): print(value)
🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...