Tutorials / Python from Scratch / Dictionaries and sets

Dictionaries and sets

13 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

Looking things up by name

A list finds things by position. But if you want the price of "tea", would you rather say "item number 3" or "tea"? A dict (dictionary) stores pairs of keys and values and finds a value by its key.

prices = {
    "tea": 120,
    "sugar": 150,
    "rice": 280,
}

print(prices["tea"])               # 120
prices["salt"] = 60                # add a new pair
prices["tea"] = 130                # change an existing one
del prices["sugar"]                # remove a pair

print(prices.get("flour"))         # None - no error
print(prices.get("flour", 0))      # 0 - our own default
print("rice" in prices)            # True - checks keys

for item, price in prices.items():
    print(f"{item:<6} Rs {price}")

print(list(prices.keys()))
print(sum(prices.values()))

Output:

120
None
0
True
tea    Rs 130
rice   Rs 280
salt   Rs 60
['tea', 'rice', 'salt']
470

The ideas behind it

Curly braces with key: value pairs create a dictionary. You read a value with square brackets and the key. Assigning to a new key adds a pair. Assigning to an existing key replaces the value. Since Python 3.7 a dictionary remembers the order in which keys were added.

Keys must be unique and unchangeable: strings, numbers and tuples work. Lists do not. Values can be anything, including lists and other dictionaries.

KeyError and get()

If you ask for a key that is not there with square brackets, Python raises a KeyError.

print(prices["flour"])    # KeyError: 'flour'

This is the mistake people make most often with dictionaries. Either check first with in, or use .get(key, default), which returns the default instead of failing. I use get when a missing key is normal and square brackets when a missing key means my data is broken and I want to know.

Nested data

Dictionaries holding dictionaries and lists look a lot like JSON, which you will meet again when you work with web APIs.

customer = {
    "name": "Ali Traders",
    "city": "Lahore",
    "orders": [
        {"id": 101, "total": 5002.0},
        {"id": 102, "total": 1800.0},
    ],
}
print(customer["orders"][1]["total"])    # 1800.0

Counting with a dictionary

A very common job is counting how many times something appears.

text = "the cat saw the dog and the dog saw the cat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)
# {'the': 4, 'cat': 2, 'saw': 2, 'dog': 2, 'and': 1}

For each word we read its current count (zero if it is new), add one, and store it back. The standard library also has collections.Counter that does this in one line, but writing it by hand once helps you understand what is happening.

Sets

A set holds unique values with no order. You create one with curly braces and no colons, or with set(). An empty {} is a dictionary, not a set, so use set() for an empty one.

visitors = ["ali", "sara", "ali", "usman", "sara"]
unique = set(visitors)
print(unique)            # {'ali', 'sara', 'usman'} - order may vary
print(len(unique))       # 3

morning = {"ali", "sara"}
evening = {"sara", "usman"}
print(morning & evening)   # in both: {'sara'}
print(morning | evening)   # in either
print(morning - evening)   # morning only: {'ali'}

Sets are fast at answering "is this item in the collection?" and they remove duplicates for free. They are not ordered, so you cannot use unique[0].

Choosing the right collection

You needUse
An ordered list that changeslist
A fixed group of related valuestuple
Lookup by name or iddict
Unique items, or membership checksset

Try it yourself

Build a dictionary for a small shop with at least four products and their stock counts. Write a loop that prints every product that has fewer than 10 left. Then ask the user for a product name and print its stock, or "not sold here" if it is missing. Use .get() so the program does not crash.

python
prices = {
    "tea": 120,
    "sugar": 150,
    "rice": 280,
}

print(prices["tea"])               # 120
prices["salt"] = 60                # add a new pair
prices["tea"] = 130                # change an existing one
del prices["sugar"]                # remove a pair

print(prices.get("flour"))         # None - no error
print(prices.get("flour", 0))      # 0 - our own default
print("rice" in prices)            # True - checks keys

for item, price in prices.items():
    print(f"{item:<6} Rs {price}")

print(list(prices.keys()))
print(sum(prices.values()))

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account