Dictionaries in Python store data as key–value pairs. To work with them effectively, you must know how to access values safely and efficiently.
[] to access a value directly by its key.get() to safely access a value and avoid KeyError.keys(), values(), and items() to access dictionary views."name")."Alice").dict[key] returns the value or raises KeyError if missing.dict.get(key, default) returns the value or a default if the key is missing.keys(), values(), and items() return dynamic views of the dictionary.for loops.A Python dictionary is defined using curly braces {} with key–value pairs:
dictionary_name = {"key1": value1, "key2": value2}
dictionary_name["key1"]dictionary_name.get("key1", default_value)dictionary_name.keys()dictionary_name.values()dictionary_name.items()You can access dictionary values using the key inside square brackets []. If the key does not exist, Python raises a KeyError.
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"]) # Alice
print(person["age"]) # 25
The get() method allows you to access a value safely. If the key does not exist, it returns None or a default value if provided.
print(person.get("name")) # Alice
print(person.get("email")) # None
print(person.get("email", "Not Found")) # Not Found
Dictionaries provide methods to access all keys, all values, or key–value pairs as dynamic views.
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 25, 'New York'])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
You can loop through the dictionary using keys or items to access both keys and values.
# Loop through keys
for key in person:
print(key, person[key])
# Loop through items
for key, value in person.items():
print(key, "->", value)
For the dictionary:
person = {"name": "Alice", "age": 25, "city": "New York"}
person["name"] prints Alice.person["age"] prints 25.person.get("email") returns None because the key "email" does not exist.person.get("email", "Not Found") returns the default string "Not Found".person.keys() returns a view object of all keys: dict_keys(['name', 'age', 'city']).person.values() returns all values: dict_values(['Alice', 25, 'New York']).person.items() returns key–value pairs: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')]).for key, value in person.items() prints lines like name -> Alice, age -> 25, etc.get() to avoid KeyError for missing keys.items() is very useful for looping through both keys and values simultaneously.keys() and values() provide dynamic views, which update automatically if the dictionary changes.get() or in operator (e.g., "email" in person).person dictionary and access a value using [] and get() for the same key.[] and see the KeyError. Then fix it using get() with a default value.for key in dict and for key in dict.keys().items() and format the output as key -> value.keys(), values(), and items() reflect the change.