π 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
| Task | Method | Safe? |
|---|---|---|
| Access value | dict[key] | β May raise KeyError |
| Safe access with fallback | dict.get(key) | β Yes |
| List all keys | dict.keys() | β Yes |
| List all values | dict.values() | β Yes |
| List all key-value pairs | dict.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