Lesson 4
Understanding Python Dictionaries: Creation, Operations, and Applications
Introduction to Dictionary Data Structure

Welcome! Today, we're diving into Python dictionaries. These store items as key-value pairs, much like a real dictionary where you look up a word (key) to find its meaning (value). By the end of this lesson, you’ll have a good grasp of dictionaries.

Understanding Dictionaries

Dictionaries in Python are unordered collections of data values. This differentiation sets them apart from lists and tuples, which have specific orders. In a dictionary, each item possesses a key associated with a specific value, enhancing its efficiency in data access and management.

Here's a simple dictionary:

Python
1# A dictionary storing names as keys and ages as values 2dictionary_example = {"Alice": 25, "Bob": 28, "Charlie": 30} 3print(dictionary_example) # Outputs: {'Alice': 25, 'Bob': 28, 'Charlie': 30}

In dictionary_example, the keys are "Alice", "Bob", and "Charlie", and the values are 25, 28, and 30, respectively. Key uniqueness is integral to the design of dictionaries - for example, that means we can only have a single key called "Alice".

Creating a Dictionary

Dictionaries are initiated by placing key-value pairs within {}. Another way to create a dictionary is by using a dict() method.

Python
1# An empty dictionary 2empty_dict_1 = {} # an empty dictionary 3empty_dict_2 = dict() # another empty dictionary 4 5# A dictionary of students and their ages 6student_age = {"Alice": 12, "Bob": 13, "Charlie": 11}

Keys and values can be of different data types.

Python
1# A dictionary with diverse key and value types 2student_info = { 3 "name": "Alice", 4 "age": 12, 5 "subjects": ["Math", "Science", "English"], 6 (90, 80): "Coordinates" # Tuple used as a key 7}
Accessing Dictionary Elements

Unlike lists, dictionaries are collections of items accessed by their keys, not by their positions.

Python
1print(student_age["Alice"]) # Outputs: 12

get() is a safer method for retrieving values as it returns None or a default value if the key is nonexistent.

Python
1print(student_age.get("David")) # Outputs: None 2print(student_age.get("David", 10)) # Outputs: 10

To check whether the key exists in the dictionary, use the in operator:

Python
1print("David" in student_age) # Outputs: False 2print("Alice" in student_age) # Outputs: True
Modifying Dictionaries

Python dictionaries are mutable, meaning we can add, modify, or delete elements.

We can add a new key-value pair like this:

Python
1student_age["David"] = 14 2print(student_age) # Outputs: {'Alice': 12, 'Bob': 13, 'Charlie': 11, 'David': 14}

Here's how to modify a value in a dictionary:

Python
1student_age["Alice"] = 15 2print(student_age) # Outputs: {'Alice': 15, 'Bob': 13, 'Charlie': 11, 'David': 14}

Here's how to delete a key-value pair:

Python
1del student_age["David"] 2print(student_age) # Outputs: {'Alice': 15, 'Bob': 13, 'Charlie': 11}
Dictionary Methods

Python dictionaries provide several handy methods, like keys(), values(), and items().

Python
1print(student_age.keys()) # Outputs: dict_keys(['Alice', 'Bob', 'Charlie']) 2print(student_age.values()) # Outputs: dict_values([15, 13, 11]) 3print(student_age.items()) # Outputs: dict_items([('Alice', 15), ('Bob', 13), ('Charlie', 11)])
Nested Dictionaries and Advanced Dictionary Operations

It isn't uncommon to nest dictionaries within other dictionaries, forming what we call nested dictionaries.

Python
1teams = { 2 "team1" : { 3 "name" : "Tigers", 4 "players" : 11 5 }, 6 "team2" : { 7 "name" : "Hawks", 8 "players" : 11 9 } 10} 11 12print(teams['team1']['name']) # Output: 'Tigers'

Nested dictionaries can be manipulated similarly to simple dictionaries.

Lesson Summary

Great work! We've delved into Python dictionaries: understanding their structure, creating and using them, and exploring their real-life applications. Next, let's reinforce this knowledge with some hands-on exercises!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.