Skip to content

Sets and Dictionaries

Use sets for unique values and dictionaries for named values.

14 min read 10 quiz questions

Sets keep unique values

A set stores unique values. Create one with braces or set(). Sets do not keep a useful item order, so sort them before printing examples.

Example 1: create and change a set
colors = {'red', 'blue', 'red'}
colors.add('green')
colors.remove('blue')
print(sorted(colors))

The repeated 'red' is kept only once. add() adds a value. remove() removes a value and raises an error if it is missing.

Set operations

Example 2: compare sets
a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
OperationMeaningExample
a | bUnion: values in either set{1, 2} | {2, 3}
a & bIntersection: shared values{1, 2} & {2, 3}
a - bDifference: values only in a{1, 2} - {2, 3}

Dictionaries connect keys to values

A dictionary maps a unique key to a value. Use square brackets when a key must exist. Use get() when a missing key should return a fallback instead of an error.

Example 3: read, add, update, and delete
student = {'name': 'Ivy', 'score': 8}
print(student['name'])
print(student.get('level', 'beginner'))
student['score'] = 10
student['city'] = 'Lima'
del student['city']
print(student)

Assigning to a new key adds it. Assigning to an existing key updates it. del removes a key and its value.

Example 4: loop through a dictionary and nest one
student = {'name': 'Ivy', 'score': 10}
print(list(student.keys()))
print(list(student.values()))
for key, value in student.items():
    print(key + ':', value)
profile = {'user': {'name': 'Ivy', 'active': True}}
print(profile['user']['name'])

Key points

  • Sets keep each value only once.
  • Sort a set before printing it when order matters.
  • Set operators compare groups of values.
  • Dictionaries map keys to values.
  • get() can safely handle a missing dictionary key.

Worked example

A libary app records who entered today; duplicates collapse in a set. Marks live in a dictionary keyed by student.

Example
visitors = ["Mim", "Rafi", "Mim"]
unique = set(visitors)
marks = {"Mim": 78, "Rafi": 64}
print(len(unique), marks["Mim"])

How it works, step by step

  1. set() keeps one copy of each value.
  2. Dictionary lookup uses the KEY in square brackets.
  3. len(set) counts distinct visitors: 2.

References & Further Reading

Related entries from PyLabs's own reference library.

  • add() (Add a single element to the set.)
  • union() (Return a new set with elements from this set and all others.)
  • get() (Look up a value safely without raising a KeyError if missing.)
  • items() (Return a dynamic view of all (key, value) pairs in the dictionary.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Create fruit = {'apple': 3, 'pear': 2}. Add 'banana' with value 5, then print fruit['banana'].

Expected output: 5

# Write your code below
Want another challenge on this module? More coding practice

Check yourself

Sets and Dictionaries quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet