🔍 How to Access Items in a Python Dictionary | TechTown.in

In Python, dictionaries are used to store data as key-value pairs — making it easy to find exactly what you need, instantly.

But how do you access specific values from a dictionary? In this post, you’ll learn how to safely and efficiently retrieve items from a Python dictionary using real-life examples.


📦 Example Dictionary

person = {
    "name": "Tanmay",
    "age": 22,
    "city": "Jaipur"
}

Here, "name", "age", and "city" are keys, and their values are what you want to access.


✅ Method 1: Access Using Square Brackets []

print(person["name"])  # Output: Tanmay

🎯 This is the direct way — but ⚠️ it throws an error if the key doesn’t exist.

print(person["email"])  # ❌ KeyError: 'email'

🛡️ Method 2: Use .get() Method (Safe Access)

print(person.get("age"))     # Output: 22
print(person.get("email"))   # Output: None

✅ No error if the key doesn’t exist. You can also set a default value:

print(person.get("email", "Not Provided"))  # Output: Not Provided

🔁 Access All Keys

for key in person:
    print(key)

Or:

print(person.keys())  # dict_keys(['name', 'age', 'city'])

🔁 Access All Values

for value in person.values():
    print(value)

Or:

print(person.values())  # dict_values(['Tanmay', 22, 'Jaipur'])

🔁 Access All Key-Value Pairs

for key, value in person.items():
    print(f"{key}: {value}")

Or:

print(person.items())
# dict_items([('name', 'Tanmay'), ('age', 22), ('city', 'Jaipur')])

🧠 Real-Life Example: Product Info

product = {
    "id": 101,
    "name": "Laptop",
    "price": 59999
}

print(product["price"])          # ₹59999
print(product.get("discount"))   # None

✅ Great for eCommerce, user profiles, and API responses.


📝 Summary – Accessing Dictionary Items in Python

TaskMethodSafe?
Access valuedict[key]❌ May raise KeyError
Safe access with fallbackdict.get(key)✅ Yes
List all keysdict.keys()✅ Yes
List all valuesdict.values()✅ Yes
List all key-value pairsdict.items()✅ Yes

🏁 Final Thoughts

Accessing items in a dictionary is one of the most essential skills in Python programming. Whether you’re working with JSON data, building forms, or parsing API responses — dictionary access methods give you full control.

Prefer .get() when you’re unsure if a key exists, and use loops to explore or process large sets of data easily.


📘 Learn more about dictionaries and Python data structures at TechTown.in