Lesson 8: Python Dictionaries and Sets

⏱️ 3 min read

In the previous lesson, we looked at Lists and Tuples, which are fantastic for keeping track of data in a specific order. However, sometimes order is not what matters most.

What if you need to look up a specific piece of information instantly, like finding a word in a real-world dictionary? Or what if you want to ensure that a collection of items contains absolutely no duplicates?

For these scenarios, Python provides two highly efficient data structures: Dictionaries and Sets.

1. Python Dictionaries (The Look-Up Tables)

A dictionary in Python allows you to store data in key-value pairs. Instead of accessing an item by its numerical index (like list[0]), you access it by its unique name, or “key.”

Think of a contacts app on your phone. You do not search for “Contact number 45” to find your friend’s phone number. You search for their name (the key) to retrieve the phone number (the value).

The Syntax: Dictionaries are created using curly braces {}, with keys and values separated by a colon :.

# Storing Indian cinema worldwide box office collections (in crores)
box_office = {
    "Dangal": 2024,
    "Baahubali 2": 1810,
    "RRR": 1316
}

Accessing Data: To retrieve a value, you simply put the key inside square brackets.

print(box_office["RRR"])  # Prints: 1316

Modifying a Dictionary: Dictionaries are mutable, meaning you can easily add new key-value pairs, update existing ones, or delete them entirely.

# Adding a new movie to the dictionary
box_office["KGF 2"] = 1200 

# Updating an existing value
box_office["RRR"] = 1387 

# Removing a key-value pair
del box_office["Dangal"]

2. Python Sets (The Unique Collections)

A set is an unordered collection of items. The absolute most important rule of a set is that all items must be unique. A set physically cannot contain duplicate values.

Sets are incredibly useful when you want to filter out duplicate data from a list, or when you want to quickly check if a specific item exists within a massive dataset.

The Syntax: Like dictionaries, sets use curly braces {}. However, they do not use key-value pairs—just single items separated by commas.

# Creating a set of supported cloud infrastructure platforms
supported_clouds = {"AWS", "Azure", "GCP"}

The Magic of Uniqueness: Watch what happens if you try to create a set with duplicate values. Python simply ignores the extras.

# AWS is listed twice here
cloud_environments = {"AWS", "Azure", "GCP", "AWS"}

print(cloud_environments)
# Output: {'Azure', 'AWS', 'GCP'} (Notice it removed the duplicate and the order changed!)

Adding and Removing Items: Because sets are unordered, you cannot use index numbers. You use specific methods to add or remove items.

active_clusters = {"cluster-alpha", "cluster-beta"}

# Adding an item
active_clusters.add("cluster-gamma")

# Removing an item
active_clusters.remove("cluster-alpha")

Mathematical Set Operations: Sets in Python support operations from mathematical set theory, like unions and intersections. This makes comparing data incredibly fast.

team_a_skills = {"Kubernetes", "AWS", "Python"}
team_b_skills = {"Java", "Python", "GCP"}

# Finding common skills (Intersection)
common_skills = team_a_skills.intersection(team_b_skills)
print(common_skills)  # Prints: {'Python'}

When to Use Which?

Here is a quick cheat sheet for choosing the right data structure in your Python programs:

  • List []: Use when order matters and you want to be able to change the data.
  • Tuple (): Use when order matters, but the data must be locked and protected from changes.
  • Dictionary {}: Use when you need to link pieces of data together (keys and values) for fast look-ups.
  • Set {}: Use when you need to guarantee that every item in your collection is unique, or when comparing groups of items.

Ready to continue?

Move on to the next lesson to keep learning.

Continue: Lesson 9: Python File Handling and Exception Handling

Tutorial: Python