Codeskill

Learn to code, step by step

Dictionaries and Sets: Python’s Powerful Collections

Python dictionaries and sets – two collections you will reach for when lists are not the right fit. Dictionaries map keys to values; sets hold unique items with no duplicates.

Dictionaries

A dictionary is a collection of key-value pairs. You look up a value by its key. Dictionaries are mutable, so you can change them after creation.

Creating a dictionary

Use curly braces {}:

person = {"name": "John", "age": 30, "city": "New York"}
print(person)

Accessing values

Pass the key in square brackets:

print(person["name"])  # Outputs: John

Adding and modifying elements

Assign to a key to add or update:

person["email"] = "john@example.com"  # Adds a new key-value pair
person["age"] = 31                    # Updates the value for the key 'age'

Removing elements

Use del or pop():

del person["city"]            # Removes the key 'city'
email = person.pop("email")   # Removes 'email' and returns its value

Iterating over a dictionary

Loop with .items() to get both key and value:

for key, value in person.items():
    print(f"{key}: {value}")

When to use dictionaries

Use a dictionary when you need to look things up by a meaningful key – person attributes, config settings, that sort of thing.

Sets

A set is an unordered collection where each item appears once. Sets are good for membership checks, removing duplicates, and set maths (union, intersection, and so on).

Creating a set

Use curly braces {} or the set() function:

fruits = {"apple", "banana", "cherry"}
print(fruits)

Accessing elements

Sets have no index. Loop through them, or test membership with in:

if "banana" in fruits:
    print("Banana is in the set")

Adding and removing elements

add() inserts an item. remove() or discard() takes one out:

fruits.add("orange")      # Adds 'orange' to the set
fruits.remove("banana")   # Removes 'banana' from the set

Set operations

Sets support union, intersection, difference, and symmetric difference:

a = {1, 2, 3}
b = {3, 4, 5}

# Union
print(a | b)  # {1, 2, 3, 4, 5}

# Intersection
print(a & b)  # {3}

# Difference
print(a - b)  # {1, 2}

# Symmetric Difference
print(a ^ b)  # {1, 2, 4, 5}

When to use sets

Use a set when you need uniqueness, set operations, or fast membership checks. Checking in on a set is faster than on a list for large collections.

Things to remember

  • Dictionaries: key-value lookups. Good for attributes and settings.
  • Sets: unique items, membership tests, deduplication.
  • Sets are unordered – no position is stored.
  • From Python 3.7 onwards, dictionaries remember insertion order.
PreviousLists and Tuples: Organizing Data in Python