How to Access a Dictionary in Python
What you’ll build or solve
You’ll read values from a Python dictionary safely and predictably.
When this approach works best
Accessing a dictionary works well when you:
Learn Python on Mimo
- Look up a value by an ID, like getting a user’s email from a
user_id. - Read configuration settings, like
"timeout"or"retries". - Pull fields from structured data, like
"profile"details inside an API response.
Avoid using a dictionary when you need ordered, position-based access. Use a list or tuple for that.
Prerequisites
- Python installed
- You know what a dictionary is
Step-by-step instructions
1) Access a value by key with square brackets
Use d[key] when the key must exist.
user= {"name":"Naomi","email":"mina@example.com"}
email=user["email"]
print(email)
What to look for:
If the key is missing, Python raises KeyError. Use get() when missing keys are possible.
2) Access a value safely with get()
Use d.get(key) when a key might be missing. It returns None instead of crashing.
user= {"name":"Naomi","email":"mina@example.com"}
phone=user.get("phone")
print(phone)
Option A: Provide a default value
user= {"name":"Naomi","email":"mina@example.com"}
phone=user.get("phone","Not provided")
print(phone)
Option B: Use in to check before access
Use this when you need to tell “missing key” apart from “key exists with value None.”
Python
user= {"phone":None}
if"phone"inuser:
print("Key exists:",user["phone"])
else:
print("Missing phone key.")
What to look for:
get() returns None for missing keys, but it also returns None when the stored value is actually None.
3) Access nested dictionaries
If a dictionary contains another dictionary, access it level by level. Combine with get() to handle missing parts.
user= {"profile": {"name":"Naomi","city":"Boston"}}
city=user["profile"]["city"]
print(city)
Option A: Safe nested access
user= {"profile": {"name":"Naomi"}}
profile=user.get("profile", {})
city=profile.get("city","Unknown")
print(city)
You can also chain get() calls:
data= {"profile": {"name":"Naomi"}}
city=data.get("profile", {}).get("city","Unknown")
print(city)
What to look for:
user["profile"]["city"] can raise KeyError at either level. Using get() with {} gives you a safe fallback for the next lookup.
Examples you can copy
Example 1: Read a config value with a default
config= {"timeout":10,"retries":3}
timeout=config.get("timeout",30)
retries=config.get("retries",1)
print(timeout,retries)
Example 2: Use a dict as a lookup table
status_labels= {200:"OK",404:"Not Found",500:"Server Error"}
code=404
label=status_labels.get(code,"Unknown")
print(label)
Example 3: Safely access user fields
user= {"name":"Naomi","email":"mina@example.com"}
name=user["name"]
phone=user.get("phone","")
print(name,phone)
Example 4: Look up multiple keys from a list
config= {
"timeout":10,
"retries":3,
"base_url":"https://example.com",
}
keys= ["timeout","retries","base_url","region"]
forkeyinkeys:
print(key,config.get(key,"not set"))
Example 5: Access a nested value with a fallback
data= {"profile": {"name":"Naomi"}}
city=data.get("profile", {}).get("city","Unknown")
print(city)
Example 6: Loop through all values to find a match
scores= {"mila":12,"ana":30,"ivan":22}
forname,scoreinscores.items():
ifscore>20:
print(name,score)
Common mistakes and how to fix them
Mistake 1: Using d[key] when the key might be missing
What you might do
user= {"name":"Naomi"}
print(user["email"])
Why it breaks
Missing keys raise KeyError.
Fix
Bash
user= {"name":"Naomi"}
print(user.get("email",""))
Mistake 2: Assuming get() tells you why a value is None
What you might do
Python
user= {"phone":None}
print(user.get("phone"))
Why it breaks
get() returns None for both “missing key” and “stored None.”
Fix
Python
user= {"phone":None}
if"phone"inuser:
print("Key exists:",user["phone"])
else:
print("Missing phone key.")
Troubleshooting
If you see KeyError, the key does not exist. Use get() or check with in before accessing.
If you see TypeError: unhashable type, you used a list or dict as a key. Use a string, number, or tuple instead.
If you get AttributeError: 'dict' object has no attribute, you tried to access a key like user.email. Use user["email"].
If nested access fails, print repr(data) and check each level, then add get() defaults where missing fields are possible.
If get() returns None unexpectedly, confirm whether the key exists with key in d.
Quick recap
- Use
d[key]when the key must exist. - Use
d.get(key, default)to handle missing keys safely. - Use
inwhen you need to distinguish “missing” from “value isNone.” - For nested data, access level by level, and use
get()with{}for safe fallbacks. - For many lookups, keep a list of keys and call
get()in a loop.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot