Python Basics: Your First Programs
Dictionaries and Sets
In this lesson you will
- Create dictionaries and read, add and remove entries
- Loop over keys, values and items
- Use sets to remove duplicates and compare collections
Introduction
A list finds things by position: "item number 2". But often you want to find things by name: "the phone number for Asha". A dictionary stores pairs of keys and values, and looks up a value from its key almost instantly.
Creating and reading a dictionary
Use curly brackets with key: value pairs.
Asking for a key that does not exist is an error. The get() method is safer and lets you set a default.
Adding, changing and removing
Quick quiz
What does my_dict.get('x', 0) return if 'x' is not a key?
Looping over a dictionary
Counting with a dictionary
A very common pattern: count how often each thing appears.
For each word, we take the current count (or 0 if it has not been seen) and add one.
Dictionaries inside lists
Real data often looks like a list of dictionaries, one per record.
Sets
A set is an unordered collection of unique items. Duplicates are removed automatically, and checking membership is fast.
An easy way to remove duplicates from a list: set(items).
Sets compare groups using maths ideas:
Note that {} on its own creates an empty dictionary. Create an empty set with set().
Quick quiz
What does set([1, 1, 2, 2, 3]) contain?
Try it yourself
Count how many times each letter appears in the word "banana", using a dictionary, and print the result. Then print how many different letters there are, using a set.
Summary
- A dictionary maps keys to values:
{"name": "Asha"}. Read withd[key]or the saferd.get(key, default). - Add or change with
d[key] = value, and loop with.items(),.keys()and.values(). - A set holds unique items and supports
&(intersection),|(union) and-(difference). - Lists of dictionaries are the usual shape of real-world records.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading