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.
prices = {"apple": 40, "banana": 10, "mango": 60}
print(prices["mango"])
print(prices["apple"])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
prices = {"apple": 40, "banana": 10, "mango": 60}
total = prices["apple"] * 3 + prices["banana"]
print("Total:", total)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:
capitals = {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris"}
country = input()
print("The capital of", country, "is", capitals[country])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.