livepython.net
CHAPTER 13Dictionaries
13.2  READ VALUES

Access Dictionary Values in Python: [], get() and in

Access a Dictionary Value by Its Key

To access a dictionary value, write the dictionary's name and the key in square brackets: prices["apple"]. Python finds the key and gives you its value.

Think of it like a coat check: you hand over your ticket (the key) and get your coat (the value) back. You don't need to know where it hangs.

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

The rules

  • Square brackets [ ] after the name, like a list index. But inside goes a key, not a position.
  • The key must match exactly: "Mango" with a capital M is a different key.
  • The value you get works like any other value: print it, store it, or do maths with it.

Use the value in a calculation

PYTHONedit me
prices = {"apple": 40, "banana": 10, "mango": 60}
total = prices["apple"] * 3 + prices["banana"]
print("Total:", total)
OUTPUT
Total: 130

The key can come from a variable

The key in the brackets can be a variable that holds a string. That's how you look up what the user types, with input() from chapter 7:

PYTHONedit me
capitals = {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris"}
country = input()
print("The capital of", country, "is", capitals[country])
OUTPUT
The capital of Japan is Tokyo

Type France in the Input box and run it again.

Avoid: quotes around the variable

capitals["country"] looks for a key that is the word country itself. Without the quotes, capitals[country] uses the value inside the variable. That one pair of quotes changes everything.

Common beginner doubt: "Can I write prices[0] to get the first value?" No. A dictionary has no positions. prices[0] looks for a key that is the number 0, which isn't there. You'll see the error it gives in the next lesson.

Write dictionary[key] to get the value stored under that key.

your turnPredict the output

What will this print?

ages = {"Sunny": 25, "Rocky": 30, "Lucky": 22} print(ages["Rocky"] + 1)
Your turn! What will this code show on the screen?
your turnFill the gap

Print Lucky's city

cities = {"Sunny": "Delhi", "Lucky": "Pune"} print(cities?)

It should print: Pune

Which piece makes this code work?

KeyError: When the Key Is Not There

When you ask a dictionary for a key it doesn't have, Python stops with a KeyError. The message shows the key it couldn't find.

Think of it like asking a librarian for a book the library doesn't own: they can't hand you anything, so they tell you it's not there.

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(ages["Lucky"])
OUTPUT
KeyError: 'Lucky'

Don't be scared of this error! It's just saying: "I looked for the key 'Lucky' and there is no such key." Every error is a clue, and this one names the exact key.

The usual causes

CauseExampleFix
the key was never addedages["Lucky"]add it, or check first
a capital letterages["sunny"]match the key exactly
a space or typoages["Rocky "]remove the extra space
a position instead of a keyages[0]ask by key, not by index

A capital letter is enough

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(ages["sunny"])
OUTPUT
KeyError: 'sunny'

"sunny" and "Sunny" are different strings, so they're different keys.

A number is a key too

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(ages[0])
OUTPUT
KeyError: 0

There are no quotes in the message this time, because the missing key is the number 0, not a string. A dictionary has no index, so 0 is looked up as a key, and it isn't there.

Input makes it common

When the key comes from input(), the user can type anything, so a KeyError can happen at any time. In the next two lessons you'll learn two ways to stay safe: get() and in.

Common beginner doubt: "My key is in the dictionary, why the error?" Print the key with quotes around it, like print("[" + key + "]"). Hidden spaces and capital letters show up right away. strip() and lower() from chapter 12 can clean them.

A KeyError means the key isn't in the dictionary: check its spelling, capitals and spaces.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnType the output

Type what this prints

menu = {"tea": 15, "coffee": 25} print(menu["coffee"] - menu["tea"])
Read the code line by line, then type the output exactly.

The get() Method and Default Values

The get() method looks up a key like square brackets do, but it never stops with a KeyError. When the key is missing, it gives back None (from chapter 5), or a default value that you choose.

Think of it like asking a friend "Do you have a pen? If not, I'll use a pencil." You always walk away with something to write with.

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(ages.get("Sunny"))
print(ages.get("Lucky"))
OUTPUT
25
None

"Lucky" isn't a key, but there's no error: get() gives None instead.

Choose your own default

Put a second value inside the brackets. get() gives it back when the key is missing:

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(ages.get("Lucky", 0))
print(ages.get("Lucky", "unknown"))
print(ages.get("Rocky", 0))
OUTPUT
0
unknown
30

The default is used only when the key is missing. Rocky is there, so his real age, 30, comes back.

The rules

You writeKey is thereKey is missing
d[key]its valueKeyError
d.get(key)its valueNone
d.get(key, default)its valuethe default

get() doesn't add the key to the dictionary. It only reads.

A safe lookup from input

PYTHONedit me
phone_book = {"Sunny": "98765", "Rocky": "91234"}
name = input()
print(phone_book.get(name, "Not found"))
OUTPUT
Not found

Change the input to Sunny and run it again.

Good and Avoid

  • Good: prices.get(item, 0) when a missing item should count as 0.
  • Avoid: get() everywhere. If a key must be there, square brackets are better: a KeyError tells you right away that something is wrong.

get(key, default) reads a value safely: the default comes back when the key is missing.

your turnPredict the output

What will this print?

stock = {"pen": 12, "book": 0} print(stock.get("book", 5))
Your turn! What will this code show on the screen?
your turnFix the code

Make it print 0 for a fruit that isn't in the dictionary

It should print: 0

prices = {"apple": 40, "mango": 60}
print(prices["kiwi"])
This code does not work yet. Fix it, then press Run.

Check If a Key Is in a Dictionary

The in keyword checks if a key is in a dictionary. "Sunny" in ages is True when "Sunny" is one of the keys, and False when it isn't. You used in with lists in chapter 9.

Think of it like checking the guest list at a party before you call someone's name: you only shout "Rocky!" if Rocky is on the list.

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print("Sunny" in ages)
print("Lucky" in ages)
print("Lucky" not in ages)
OUTPUT
True
False
True

in checks the keys, not the values

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
print(25 in ages)
OUTPUT
False

25 is a value here, not a key, so the answer is False. With a dictionary, in only ever looks at the keys.

in with if and else

Check first, then use square brackets safely, with if from chapter 8:

PYTHONedit me
prices = {"apple": 40, "mango": 60}
fruit = input()
if fruit in prices:
    print(fruit, "costs", prices[fruit])
else:
    print("Sorry, we have no", fruit)
OUTPUT
Sorry, we have no kiwi

Try apple in the Input box, then try Apple. The capital letter makes it a different key.

in or get()?

UseWhen
if key in d:you want to do something different when the key is missing, like print a message
d.get(key, default)a missing key should simply count as a default value, like 0

Both keep you away from the KeyError. Pick the one that reads most clearly.

Common mistake: writing if prices[fruit]: to test if a key exists. That line itself stops with a KeyError when the key is missing. Test with in instead.

key in d is True when the key exists; with a dictionary, in checks keys only.

your turnPick the right idea

marks = {"Sunny": 90, "Rocky": 75}. What is 90 in marks?

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

What will this print?

name = " Lucky " print(name.strip().lower())
Your turn! What will this code show on the screen?

Practice: Read values

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

  1. 112.Python Program to Look Up a Phone NumberEasySolve
  2. 113.Python Program to Calculate a Fruit BillMediumSolve