Accessing Dictionary Items
You can access dictionary items by referring to their key name, inside square brackets, or by using the get()
method.
Using Square Brackets
Example: Accessing a Value by Key
# Accessing dictionary items
person = {"name": "Vijay", "age": 25, "city": "Madurai"}
name = person["name"]
print("Name:", name)
Name: Vijay
Using get()
Method
Example: Accessing a Value Using get()
# Using get() method
age = person.get("age")
print("Age:", age)
Age: 25
Accessing Keys, Values, and Items
Example: Using keys()
, values()
, and items()
# Accessing keys, values, and items
keys = person.keys()
values = person.values()
items = person.items()
print("Keys:", keys)
print("Values:", values)
print("Items:", items)
Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['Vijay', 25, 'Madurai'])
Items: dict_items([('name', 'Vijay'), ('age', 25), ('city', 'Madurai')])
Explanation: The keys()
, values()
, and items()
methods return views of the dictionary's keys, values, and key-value pairs, respectively. These views can be iterated over in loops.