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".
phone_book = {"Sunny": "98765", "Rocky": "91234", "Lucky": "99887"}
print(phone_book){'Sunny': '98765', 'Rocky': '91234', 'Lucky': '99887'}This dictionary holds three pairs. "Sunny" is a key and "98765" is its value.
The words
| Word | Meaning | In the example |
|---|---|---|
| key | the name you look up | "Rocky" |
| value | what 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:
contacts = ["Sunny", "98765", "Rocky", "91234"]
print(contacts[3])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.