Sets, (Tuples), and Dictionaries#
Learning Objectives
Questions:
What are sets and dictionaries in Python, and how can we use them?
Objectives:
Understand the purpose of sets and dictionaries.
Use sets to remove duplicates from lists.
Create and manipulate dictionaries.
Sets#
A set in Python is a built-in data type that represents a collection of unique, unordered items. Sets are similar to lists, but they automatically remove duplicate entries and do not maintain order.
Why use sets?#
To eliminate duplicate values from a list.
To carry out set operations like union, intersection, difference, and symmetric difference.
Removing duplicates from a list#
Below, we have a list of book titles that contains duplicates. By converting the list to a set, we remove duplicates automatically - because sets only allow unique items. We then convert it back to a list to keep working with it in list form.
books = ["1984", "Brave New World", "1984", "Fahrenheit 451"]
unique_books = list(set(books))
print(unique_books)
Since sets are unordered, the order of elements in unique_books
may differ from the original list.
Set operations#
Set operations are inspired by mathematics and let you compare two sets to find relationships between their elements:
Operation |
Code |
Description |
---|---|---|
Union |
|
All elements from both sets |
Intersection |
|
Elements common to both sets |
Difference |
|
Elements in |
Symmetric difference |
|
Elements in either |

Visualisation of set operations in Python: union (|), intersection (&), difference (-), and symmetric difference (^).
Example:
a = {"apple", "banana", "cherry"}
b = {"banana", "cherry", "date"}
print(a | b) # {'apple', 'banana', 'cherry', 'date'}
print(a & b) # {'banana', 'cherry'}
print(a - b) # {'apple'}
print(a ^ b) # {'apple', 'date'}
These operations are useful when comparing datasets or filtering information.
For example, you can use them to find shared elements between two lists, or to detect what’s missing from one compared to another.
(Tuples)#
What are tuples?
A tuple is another type of collection in Python. It is similar to a list, but unlike lists, tuples are immutable - once you create a tuple, you cannot change its contents.
Why use tuples?
When you want to store a fixed collection of items.
When immutability is important (e.g. as keys in a dictionary).
You create tuples with parentheses:
coordinates = (5.4, 6.7)
Tuples are often used for data that belongs together, such as coordinates, RGB color values, or return values from functions.
For more, see W3Schools on Tuples.
Dictionaries#
A dictionary is one of the most powerful and flexible data types in Python. It allows you to store and retrieve data using keys instead of index numbers. Dictionaries are useful when you want to associate a value with a label or identifier.
Structure#
A dictionary consists of key-value pairs, where:
Keys must be unique and immutable (e.g., strings, numbers, or tuples).
Values can be of any type - such as strings, integers, booleans, lists, or even other dictionaries. This flexibility allows you to store complex, nested data structures.
Why use dictionaries?#
To represent structured data (e.g., a book’s title, author, and year).
To model mappings between elements (e.g., usernames and passwords).
To access data by a meaningful name rather than a numeric index.
Creating and accessing a dictionary#
When creating a dictionary, you use curly braces {}
and define one or more key-value pairs.
Each pair consists of a key, followed by a colon :
, and then the value.
Multiple pairs are separated by commas ,
.
The syntax looks like this:
dictionary_name = {
"key1": value1,
"key2": value2,
...
}
Keys must be unique and immutable - most often strings or numbers.
Values can be of any data type: strings, numbers, lists, other dictionaries, etc.
In the example below:
book = {
"title": "1984",
"author": "George Orwell",
"year": 1949
}
"title"
,"author"
, and"year"
are the keys."1984"
,"George Orwell"
, and1949
are the corresponding values.
This structure makes it easy to look up or update information using the key, without needing to know the position of the data like you would in a list.
Accessing values in a dictionary#
Once a dictionary is created, you can retrieve the value associated with a specific key. This is similar to looking up a word in a dictionary to get its definition.
There are two main ways to access values:
Using square brackets
[]
with the key name. This is straightforward but will raise an error if the key does not exist.Using the
.get()
method, which safely returnsNone
(or a custom default value) if the key is not found.
print(book["author"])
print(book.get("year"))
Updating and modifying dictionaries#
Once a dictionary is created, we can continue working with it by changing the value of an existing key, adding new key-value pairs, or removing existing ones. These operations are useful when we want to update a data record, add more information, or clean up unnecessary entries.
Dictionaries are mutable, which means you can update them after they are created. This makes them very flexible and practical when working with dynamic data.
You can:
Change existing values by assigning a new value to an existing key.
Add new key-value pairs by assigning a value to a new key.
Delete key-value pairs using the
del
statement.
These operations allow you to keep your dictionary up to date with new information, modify incorrect entries, or remove values you no longer need.
book["year"] = 1950 # update
book["genre"] = "Dystopian" # add
del book["genre"] # delete
Looping through dictionaries#
When we want to examine all the contents of a dictionary, we can loop through it. We can access just the keys, or both keys and values. This is useful when printing, filtering, or transforming the data.
This first loop iterates through the dictionary using just the keys.
In each iteration, the variable key
holds the name of a key in the dictionary, and book[key]
retrieves the corresponding value.
for key in book:
print(key, ":", book[key])
This second loop uses the .items()
method, which returns both the key and the value for each pair in the dictionary.
This makes the code cleaner and more readable when you need both parts.
for key, value in book.items():
print(f"{key}: {value}")
Both loops print all entries in the dictionary, but the second version is preferred when you want to work directly with both key and value at the same time.
Common dictionary methods#
|
Returns a view of all keys |
|
Returns a view of all values |
|
Returns key-value pairs as tuples |
|
Returns the value for a key |
Nested dictionaries#
A dictionary can contain other dictionaries as its values. This is especially useful when dealing with structured or hierarchical data. In the example below, we create a library
dictionary where each book title maps to another dictionary containing the author and year.
This is an example of a nested dictionary, where each key in the outer dictionary maps to another dictionary as its value:
library = {
"1984": {"author": "George Orwell", "year": 1949},
"Dune": {"author": "Frank Herbert", "year": 1965}
}
print(library["Dune"])
print(library["Dune"]["author"])
In this case, library
is a dictionary that stores information about books. Each book title (e.g., "1984"
or "Dune"
) is a key, and the value is another dictionary containing details like "author"
and "year"
.
To access the author of “Dune”, we use two levels of square brackets:
library["Dune"]
returns the inner dictionary:{"author": "Frank Herbert", "year": 1965}
library["Dune"]["author"]
retrieves the value associated with the"author"
key inside that inner dictionary.
This type of structure is useful when you need to organise complex or hierarchical data in a way that is easy to access and understand.
Exercises#
Exercise 2: Add and delete#
What does this code print?
book = {"title": "1984", "author": "George Orwell"}
book["genre"] = "Dystopian"
del book["title"]
print(book)
Solution
The key 'genre'
is added, and the key 'title'
is deleted. The final dictionary only contains 'author'
and 'genre'
.
{'author': 'George Orwell', 'genre': 'Dystopian'}
Exercise 3: Loop through books#
Create a dictionary of three books and print their titles and years using a loop.
Solution
We define a dictionary with book titles as keys and years as values. Then we loop through the dictionary using .items()
to print each entry in a formatted string.
books = {
"1984": 1949,
"Dune": 1965,
"Brave New World": 1932
}
for title, year in books.items():
print(f"{title} was published in {year}.")
Exercise 4: Remove duplicates#
Given this list:
authors = ["Orwell", "Huxley", "Orwell", "Bradbury"]
Use a set to remove duplicates and convert it back to a list.
Solution
We convert the list to a set to remove duplicates, then back to a list to maintain list functionality.
authors = ["Orwell", "Huxley", "Orwell", "Bradbury"]
unique_authors = list(set(authors))
print(unique_authors)
Key points#
Sets are useful for filtering out duplicates and checking membership.
Tuples are immutable sequences and useful when fixed data is needed.
Dictionaries store data in labeled key-value pairs and are essential for handling structured data.
Use
.items()
,.keys()
, and.values()
to interact with dictionaries.These collection types help you manage, structure, and retrieve data efficiently in Python.