Accessing Dictionary Values Simplified: 5 Easy Examples
You can access values in a dictionary using keys. Here are five examples demonstrating different ways to access values in a dictionary:
- Accessing a value by key directly:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_a = my_dict['a']
print(value_a) # Output: 1
- Using the
get()
method:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_b = my_dict.get('b')
print(value_b) # Output: 2
- Handling non-existent keys with
get()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_d = my_dict.get('d', 'Key not found')
print(value_d) # Output: Key not found
- Accessing values in a loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(my_dict[key])
# Output:
# 1
# 2
# 3
- Using a conditional statement to access values:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_check = 'b'
if key_to_check in my_dict:
print(my_dict[key_to_check])
else:
print("Key not found")
# Output: 2
These examples illustrate various ways to access values stored in a Python dictionary.