Skip to content

Dictionaries and Sets

Programming Python Difficulty 1/5

Beginning of the lesson

Dictionaries and Sets

Store things by name, and keep a list of unique things

Big Idea: A dictionary stores pairs of key -> value, so you can look something up by name instead of by position. A set is a bag of items where every item is unique — duplicates disappear.
By the end you will be able to:
  • create a dictionary and read a value by its key,
  • add, change, and remove dictionary items safely,
  • loop over keys, values, and pairs,
  • build a set to remove duplicates and check membership fast.

1. What is a dictionary?

Think of a real paper dictionary: you look up a word and find its meaning. A Python dictionary works the same way — you look up a key and get its value.

A phone's contacts app is a perfect example: you type a name (the key) and it gives you a phone number (the value). You do not care that the name is the 5th contact — you find it by name.

key value "Sam" "Mia" "Leo" 12 11 13
Each key on the left points to exactly one value on the right.

We write a dictionary with curly braces { }, and each pair is key: value:

# A dictionary maps keys to values
ages = {"Sam": 12, "Mia": 11, "Leo": 13}

print(ages["Mia"])

Output:

11

The keys here are the names "Sam", "Mia", "Leo". Writing ages["Mia"] asks the dictionary: "what value is stored under Mia?" The answer is 11.

2. Adding, changing, and removing

A dictionary can grow and change. Use dict[key] = value to add a new pair or to change an existing one, and del to remove a pair:

ages = {"Sam": 12, "Mia": 11}

ages["Leo"] = 13     # add a new key
ages["Sam"] = 15     # change an existing value
del ages["Mia"]      # remove a key

print(ages)

Output:

{'Sam': 15, 'Leo': 13}

Because "Sam" already existed, writing to it changed the value from 12 to 15. Because "Leo" was new, it was added. And del ages["Mia"] removed Mia completely.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers