Accessing Keys and Values
Dictionaries in Python store data as key-value pairs. To access specific elements, you can use the following methods:
1. Direct Access:
- Use the key within square brackets to access the corresponding value.
Python
my_dict = {"name": "Alice", "age": 30}
name = my_dict["name"] # Access the value associated with the key "name"
print(name) # Output: Alice
2. get() Method:
- The get() method provides a more flexible way to access values. It takes the key as the first argument and an optional default value as the second argument. If the key doesn't exist, it returns the default value.
Python
city = my_dict.get("city", "Unknown") # Access the value for "city", or "Unknown" if it doesn't exist
print(city) # Output: Unknown
3. Iterating Over Keys and Values:
- Use the items() method to iterate over key-value pairs.
Python
for key, value in my_dict.items():
print(key, value)
4. Accessing Keys and Values Separately:
- Use the keys() and values() methods to retrieve the keys and values separately.
Python
keys = my_dict.keys()
values = my_dict.values()
Example:
Python
person = {"name": "John", "age": 35, "city": "New York"}
# Direct access
name = person["name"]
print(name) # Output: John
# Using get()
age = person.get("age", 0)
print(age) # Output: 35
# Iterating over key-value pairs
for key, value in person.items():
print(key, value)
# Accessing keys and values separately
keys = person.keys()
values = person.values()
print(keys) # Output: dict_keys(['name', 'age', 'city'])
print(values) # Output: dict_values(['John', 35, 'New York'])
By understanding these methods, you can effectively access and manipulate data within dictionaries in Python.