Python Introduction to Dictionaries
Table of Contents + β
In the last lesson you learned Set Methods. You saw how a set holds a group of unique items. Now we move to something you will reach for almost every day in Python. That tool is the dictionary. You use it when each piece of data has a name. Then you look it up by that name.
π€ Why Dictionaries?
Say you want to store one personβs details. Their name, their age, and the city they live in. With a list, you might do this.
This stores the three values in order. Then it tries to read them back by position.
person = ["Alex", 29, "Lagos"]
print(person[0]) # nameprint(person[1]) # ageprint(person[2]) # cityOutput
Alex29LagosIt works. But there is a real problem hiding here. You have to remember that position 0 is the name. Position 1 is the age. Position 2 is the city. Now imagine a list with twenty values. Was the price at index 2 or index 12? You will spend a lot of time counting positions. One wrong number gives you the wrong answer. And there is no error to warn you.
A dictionary fixes this. Instead of looking things up by position, you look them up by a name you choose. So you ask for "price" and you get the price. No counting. The name itself tells you what the value means.
π§© What Is a Dictionary?
A dictionary stores data as key-value pairs. Each piece of data has two parts.
- the key is the name you use to find the value (like
"age") - the value is the actual data behind that name (like
29)
Think of a real paper dictionary. You do not flip to βpage 412β to find a word. You look up the word itself. Next to it sits the meaning. The word is the key. The meaning is the value. A Python dictionary works the same way. You give it a key. It hands you the value.
Or picture the contacts app on your phone. You do not scroll to βcontact number 47β. You type a name. The phone shows you that personβs number. The name is the key. The number is the value.
π Creating a Dictionary
You build a dictionary with curly braces { }. Inside, you write each pair as key: value. You separate the pairs with commas.
Here is the same person record from before. This time it is a dictionary.
person = { "name": "Alex", "age": 29, "city": "Lagos"}
print(person)Output
{'name': 'Alex', 'age': 29, 'city': 'Lagos'}Letβs read that slowly.
- the curly braces
{ }mark the start and end of the dictionary - on each line we have a pair:
"name"is the key,"Alex"is the value, and the colon:joins them - a comma separates one pair from the next
The keys here are text, so they go in quotes. The values can be any type you like. See how "name" holds text but "age" holds a plain number. A single dictionary can mix types freely.
Tip
Spreading the pairs over several lines like above is just for readability. You can also write it on one line: person = {"name": "Alex", "age": 29, "city": "Lagos"}. Python treats both exactly the same.
π Reading a Value by Its Key
This is the whole point of a dictionary. To get a value, you write the dictionary name. Then you put the key in square brackets [ ].
This reads each field of the person record by its name.
person = { "name": "Alex", "age": 29, "city": "Lagos"}
print(person["name"])print(person["age"])print(person["city"])Output
Alex29LagosLook at how clear that reads. person["name"] asks for the name. person["city"] asks for the city. You are not counting positions and hoping you got it right. You ask for what you want by name. And you get it. That is the comfort a dictionary gives you.
You can drop the looked-up value straight into a sentence too. Here we build a friendly line of text with an f-string.
person = { "name": "Alex", "age": 29, "city": "Lagos"}
print(f"{person['name']} is {person['age']} and lives in {person['city']}.")Output
Alex is 29 and lives in Lagos.Note
Inside an f-string the outer quotes are double quotes, so the keys inside use single quotes, like person['name']. Mixing them this way keeps Python from getting confused about where the text ends.
π« Keys Are Unique
A dictionary cannot hold the same key twice. Each key points to exactly one value. Keys must stay unique. But if you write the same key more than once, Python does not raise an error. It just keeps the last one. It quietly throws away the earlier value.
Watch what happens when "age" appears twice.
person = { "name": "Alex", "age": 29, "age": 35}
print(person["age"])Output
35The first "age" is gone. Only the last value, 35, stays. So treat each key as a name that belongs to one value at a time. If you assign to a key that already exists, you are replacing what was there. You are not adding a second copy.
Values, on the other hand, are free to repeat. Two different people can both have the age 29. It is only the keys that must each be different.
π§ List vs Dictionary
Here is the difference side by side, so it stays clear.
| Question | List | Dictionary |
|---|---|---|
| How do you find a value? | by its position (index) | by its key (a name) |
| What does access look like? | scores[2] | person["age"] |
| Brackets used to build it | square [ ] | curly { } |
| Good when | order matters, items are similar | each value has a clear name |
A list is great for a row of similar things, like a list of test scores. A dictionary shines when each value means something different and deserves its own name.
β οΈ Common Mistakes
A few slips trip people up early on. Watch for these.
- Using the wrong brackets. A dictionary is built with curly braces, not square ones.
# β Avoid: square brackets make a list, not a dictionaryperson = ["name": "Alex"] # this is a syntax error
# β
Good: curly braces with key: value pairsperson = {"name": "Alex"}- Forgetting the quotes on a text key. A word with no quotes looks like a variable name to Python.
# β Avoid: name has no quotes, Python looks for a variable called nameperson = {name: "Alex"}
# β
Good: the key is text, so it goes in quotesperson = {"name": "Alex"}- Reading the value with the wrong brackets. You access a value with square brackets, even though you built the dictionary with curly ones.
person = {"name": "Alex"}
# β Avoid: curly braces do not read a value# print(person{"name"})
# β
Good: square brackets around the keyprint(person["name"])β Best Practices
Small habits that keep your dictionaries readable.
- Give keys clear, descriptive names like
"email"or"city", not vague ones like"x". - Keep one kind of thing per dictionary. A person record holds person details, not a mix of unrelated data.
- Stick to one style for your keys. If you use text keys, use text keys throughout, so reading the value is predictable.
- When a dictionary has several pairs, write each pair on its own line. It reads far more easily than one long line.
π§© What Youβve Learned
A quick recap of what you can now do.
- β A dictionary stores data as key-value pairs, so you look things up by name instead of by position
- β
You create one with curly braces
{ }and write each pair askey: value - β
You read a value with square brackets around its key, like
person["age"] - β Keys must be unique, and assigning to an existing key replaces its value
- β A dictionary is the right choice when each value has a clear name of its own
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
How do you read the value stored under the key "city" in a dictionary named person?
Why: You access a dictionary value by putting its key inside square brackets, so person["city"] returns that value.
- 2
Which brackets do you use to create a dictionary?
Why: A dictionary is built with curly braces, with each pair written as key: value.
- 3
What happens if the same key appears twice when you create a dictionary?
Why: Keys are unique, so Python keeps only the last value assigned to a repeated key.
- 4
Why is a dictionary often better than a list for storing one person's details?
Why: A dictionary lets you ask for a value by its key, so you never have to remember which index held which detail.
π Whatβs Next?
Now that you can build a dictionary and read from it, the next step is to change one: add new pairs, update values, and remove things you no longer need.