Q.Write a program to input your friend’s, names and their phone numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Concept understanding — Dictionary Key Access
Dictionary Key Access
Imagine you have a physical address book. Each entry has a name (like "Ravi") and a phone number (like "[PII:phone]"). To find Ravi's number, you don't flip through every page — you look up "Ravi" directly. That name is the key, and the number is the value.
A dictionary in programming is exactly that: a collection of key-value pairs. The key is what you know; the value is what you want to retrieve. Key access is the operation of giving the dictionary a key and getting back the value tied to it.
The Intuition
Think of a real dictionary (the book). You look up a word (the key) to find its definition (the value). You never look up a definition to find the word — that would be backwards. Similarly, in a Python dictionary, you always access values by their keys, never the other way around.
Keys must be unique and immutable (strings, numbers, tuples). Values can be anything — numbers, strings, lists, even other dictionaries.
The Precise Statement
In Python, dictionary key access is done using square brackets [] with the key inside, or the .get() method.
Syntax:
dictionary_name[key]
or
dictionary_name.get(key, default_value)
Example:
student = {"name": "Anjali", "age": 17, "grade": "A"}
print(student["name"]) # Output: Anjali
print(student.get("age")) # Output: 17
What Happens Under the Hood
When you write student["name"], Python:
- Takes the key
"name". - Computes its hash (a fixed-size number derived from the key's content).
- Uses that hash to jump directly to the memory location where the value
"Anjali"is stored.
This is why dictionary access is fast — it doesn't scan through all entries. It's a direct lookup, like using an index in a book's index rather than reading every page.
If you use a key that does not exist with square brackets, Python raises a KeyError and your program crashes. The .get() method is safer — it returns None (or a default you provide) instead of crashing.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.