T
Tech Town
Log InSign Up Free
← Back to Blog

June 19, 2025 · admin

Access Items


πŸ” 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