livepython.net
CHAPTER 13Dictionaries
13.1  DICTIONARY

Python Dictionary: Store Data in Key-Value Pairs

What Is a Dictionary in Python?

A dictionary stores values under names. Each value has a key (its name), and you use the key to find the value. Together, a key and its value make a key-value pair.

Think of it like the contacts on your phone: you look up a name (the key) and get a phone number (the value). You never ask for "contact number 2". You ask for "Rocky".

PYTHONedit me
phone_book = {"Sunny": "98765", "Rocky": "91234", "Lucky": "99887"}
print(phone_book)
OUTPUT
{'Sunny': '98765', 'Rocky': '91234', 'Lucky': '99887'}

This dictionary holds three pairs. "Sunny" is a key and "98765" is its value.

The words

WordMeaningIn the example
keythe name you look up"Rocky"
valuewhat is stored under the key"91234"
pair (or item)one key with its value"Rocky": "91234"

Why not a list?

You could put the same data in a list from chapter 9:

PYTHONedit me
contacts = ["Sunny", "98765", "Rocky", "91234"]
print(contacts[3])
OUTPUT
91234

It works, but who remembers that Rocky's number is at index 3? Add one contact at the front, and every index moves. A dictionary lets you ask for "Rocky" by name, so the position doesn't matter.

Common beginner doubt: "Why does print() show single quotes when I typed double quotes?" That's Python's own way of showing strings inside a dictionary, the same as with lists. Both quotes mean the same thing.

A dictionary stores key-value pairs: you look up a value by its key, not by its position.

your turnPick the right idea

In the pair "Lucky": "99887", which part is the key?

Think about it, then pick one.
your turnPredict the output

What will this print?

ages = {"Sunny": 25, "Rocky": 30} print(ages)
Your turn! What will this code show on the screen?

How to Create a Dictionary

You create a dictionary with curly brackets {}. Inside, each pair is written as key: value, and a comma separates one pair from the next.

Think of it like filling in a form: every line has a label on the left (the key), a colon, and your answer on the right (the value).

PYTHONedit me
student = {"name": "Sunny", "age": 15, "grade": 9.5, "passed": True}
print(student)
OUTPUT
{'name': 'Sunny', 'age': 15, 'grade': 9.5, 'passed': True}

The rules

  • Curly brackets {} around the whole dictionary.
  • A colon : between each key and its value.
  • A comma , between pairs.
  • Keys are usually strings, like "name". Numbers work as keys too.
  • Values can be anything you know: a string, an int, a float, a boolean, even a list.

Long dictionaries on several lines

When a dictionary gets long, put one pair on each line. Python reads it as one dictionary until the closing }:

PYTHONedit me
prices = {
    "apple": 40,
    "banana": 10,
    "mango": 60,
}
print(prices)
OUTPUT
{'apple': 40, 'banana': 10, 'mango': 60}

The comma after the last pair is allowed, and it makes adding a new line easy.

An empty dictionary

{} with nothing inside is an empty dictionary. You'll fill one up in topic 3. type() from chapter 4 calls a dictionary dict:

PYTHONedit me
cart = {}
print(cart)
print(type(cart))
OUTPUT
{}
<class 'dict'>

Avoid: = instead of :

Inside a dictionary, a key and its value are joined by a colon, not by =:

PYTHONedit me
student = {"name" = "Sunny"}
OUTPUT
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

Don't be scared of this error! Python sees = and guesses you wanted to store or compare something. Its hint about == is wrong here: the real fix is a colon, {"name": "Sunny"}.

Curly brackets around it, a colon inside each pair, a comma between pairs.

your turnFill the gap

Complete the dictionary

pet = {"name" ? "Rocky", "legs": 4} print(pet)

It should print: {'name': 'Rocky', 'legs': 4}

Which piece makes this code work?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Unique Keys and Counting Pairs with len()

In a dictionary, every key is unique: one key can appear only once. Values don't have this rule, so two keys may hold the same value.

Think of it like lockers at school: each locker has its own number (the key), but two lockers can hold the same kind of bag (the value).

Same key twice? The last one wins

If you write a key twice, Python doesn't stop with an error. It keeps one pair, with the last value:

PYTHONedit me
scores = {"Sunny": 70, "Rocky": 85, "Sunny": 95}
print(scores)
OUTPUT
{'Sunny': 95, 'Rocky': 85}

The 70 is gone, without a warning. So check your keys for copies, especially in a long dictionary.

Same value twice? No problem

PYTHONedit me
ages = {"Sunny": 12, "Rocky": 12, "Lucky": 14}
print(ages)
OUTPUT
{'Sunny': 12, 'Rocky': 12, 'Lucky': 14}

Count the pairs with len()

len() from chapter 5 works on dictionaries too. It counts the pairs, not the keys and values separately:

PYTHONedit me
ages = {"Sunny": 12, "Rocky": 12, "Lucky": 14}
print(len(ages))
print(len({}))
OUTPUT
3
0

The rules

PartCan it repeat?Can it be a list?
keyno, the last copy winsno: use a string or a number
valueyesyes

Common beginner doubt: "Is "sunny" the same key as "Sunny"?" No. Keys are compared exactly, like strings with == in chapter 5, so a capital letter makes it a different key.

Each key appears once (the last copy wins); len() counts the pairs.

your turnType the output

Type what this prints

stock = {"pen": 5, "book": 2, "pen": 9} print(len(stock))
Read the code line by line, then type the output exactly.
your turnPredict the output

What will this print?

stock = {"pen": 5, "book": 2, "pen": 9} print(stock)
Your turn! What will this code show on the screen?

Dictionary or List: Which One to Use?

A list keeps values in a row and finds them by position. A dictionary keeps values under names and finds them by key. Choosing the right one makes your code much easier to read.

Think of it like a queue and a coat check. In a queue, people are found by their place: first, second, third. At a coat check, you get your coat back by your ticket name, wherever it hangs.

The difference

ListDictionary
brackets[ ]{ }
holdsvalueskey-value pairs
you find a value byits index: 0, 1, 2its key: "Sunny"
good fora row of similar thingsfacts about one thing, or a lookup table

Pick a list when the order is the point

PYTHONedit me
queue = ["Sunny", "Rocky", "Lucky"]
print(queue[0], "is first")
OUTPUT
Sunny is first

Pick a dictionary when each value has a name

PYTHONedit me
car = {"brand": "Tata", "year": 2021, "color": "red"}
print(car)
OUTPUT
{'brand': 'Tata', 'year': 2021, 'color': 'red'}

With a list, ["Tata", 2021, "red"], you'd have to remember that index 1 means the year. With a dictionary, the key says it.

What about the order?

A dictionary keeps its pairs in the order you added them, so print() always shows them in that order. But there is no "first item" to ask for: a dictionary has no index 0. You always ask by key, as the next topic shows.

Common beginner doubt: "Can a dictionary hold a list?" Yes! A value can be a list, like "marks": [80, 92, 75]. You'll use that in the last topic.

Use a list for a row of things in order; use a dictionary when every value has a name.

your turnPick the right idea

You want to store a book's title, author and number of pages. Which fits best?

Think about it, then pick one.
your turnPredict the output

What will this print?

nums = [5, 10, 15, 20] print(nums[1:3])
Your turn! What will this code show on the screen?

Practice: Dictionary

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 110.Python Program to Create a Dictionary from InputEasySolve
  2. 111.Fix the Broken Phone Book DictionaryMediumSolve