University of Glasgow · FACULTY OF COMPUTER SCIENCE

COMPSCI4039 Chap.9 Dictionaries and Sets

- one subject, every graph, every model, every mark
7 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 9 of 10 · COMPSCI4039

Dictionaries and Sets

Dictionaries and Sets covers collections in which items are reached by a key rather than a position. A dictionary is a collection of key and value pairs, each behaving like a variable association, and the key may be any unchangeable Python value such as a str, int or tuple (a list cannot be a key). The lecture describes two ways to use the same structure.

An index-style dictionary resembles a book index or paper dictionary, with many keys of the same kind mapping to values of the same format for fast look-up. A record-card dictionary describes a single thing, with each key naming an attribute. Dictionaries are created with braces, read and updated with square brackets, and extended simply by assigning to a new key.

The in operator tests whether a key is present, a for loop visits the keys, and asking for a missing key raises an error, which get avoids by supplying a default. Because keys are unique, storing a value under an existing key replaces the old one. Sets hold unique values without order, support union, intersection and difference, and give a quick way to remove duplicates from a list.

In this chapter

What this chapter covers

  • 01

    Keys instead of positions

  • 02

    Index-style and record-card dictionaries

  • 03

    Creating, reading, updating and adding entries

  • 04

    Membership tests and looping over keys

  • 05

    Counting with get and a default

  • 06

    Unique keys and overwriting

  • 07

    Sets, set operations and removing duplicates

Worked example · free

Count letters with a dictionary

Q [4 marks]. After freq = {} and, for each character ch in "banana", freq[ch] = freq.get(ch, 0) + 1, what does freq hold?
On the left, many room codes each map to a capacity, like a book index built for fast look-up.On the left, many room codes each map to a capacity, like a book index built for fast look-up. On the right, one student is described by named attributes, like a single record card.index stylerecord-card styleGH101120BO21040SW30560"name"Isla"year"3"modules"[...]
On the left, many room codes each map to a capacity, like a book index built for fast look-up. On the right, one student is described by named attributes, like a single record card.
  • 1The first b is new, so get returns 0 and freq["b"] becomes 1. This mark weighting is not a university marking scheme.
  • 1Each a adds one to its count; a occurs three times, ending at 3.
  • 1n occurs twice, ending at 2.
  • 1Keys appear in the order first inserted: b, a, n.
freq holds {'b': 1, 'a': 3, 'n': 2}, one entry per distinct letter with its count.
Sia tip — Use get with a default of 0 whenever a key might not exist yet; square brackets alone would stop the program.
Glossary

Key terms

Key-value pair
One entry in a dictionary, linking a unique key to its associated value.
Record-card style
Using a dictionary to describe one thing, with each key naming an attribute.
Set
An unordered collection of unique values that supports union and intersection.
FAQ

Dictionaries and Sets FAQ

What happens if I look up a key that is not there?

Square-bracket look-up of a missing key stops the program with an error. Check first with the in operator, or use get with a default value, which returns the default instead of failing.

Can two entries share the same key?

No. Keys are unique, so assigning a value to a key that already exists replaces the earlier value without warning. When inverting a mapping in which several keys share a value, store a list of keys as each new value.

When is a set more useful than a list?

A set is useful when only membership matters and duplicates should disappear. It answers whether a value is present quickly and supports union, intersection and difference, but it keeps no order and has no indexes.

Does a for loop over a dictionary give keys or values?

A for loop over a dictionary visits its keys. To reach each value, look it up inside the loop with the key, as in stock[name]. This pattern drives most dictionary exercises in the lab, such as listing the parts whose quantity is low or totalling the prices of the items in a basket.

Study strategy

Exam move

Work with dictionaries through small cases drawn from everyday records. Model a price list, a stock sheet and a phone directory as index-style dictionaries, and a student or a product as a record-card dictionary, then write a few lines to read, update and add entries in each. For every loop over a dictionary, say aloud that the loop variable receives keys and that the value comes from looking each key up.

Practise the counting pattern with get until you can write it without notes, and try it on words and on letters. Then rehearse the overwrite behaviour by inverting a mapping that contains a repeated value, predicting which entry survives. Draw the lecture's exercise structures, including dictionaries that hold lists, and trace the indexing paths.

For sets, work out unions, intersections and differences by hand on two small sets, and convert a list with duplicates to a set and back, noting that order may change. Finally, summarise when to choose a list, a tuple, a dictionary or a set.

Working through Dictionaries and Sets in COMPSCI4039? Sia is AskSia’s AI Computer Science tutor — ask any COMPSCI4039 Dictionaries and Sets question and get a clear, step-by-step explanation grounded in how COMPSCI4039 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 26 of your subjects at University of Glasgow, plus 1,000+ more Bibles across the AskSia library.
Sia - your COMPSCI4039 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works