search

How to access values in a dictionary in Python?

In Python, you can access values in a dictionary by using the corresponding key. Dictionary keys are used to uniquely identify and retrieve the associated values. There are a few ways to access values in a dictionary:

Square Bracket Notation: You can use square brackets [] and provide the key inside them to access the value associated with that key. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

print(my_dict['name'])  # Output: John
print(my_dict['age'])   # Output: 30
print(my_dict['city'])  # Output: New York

get() Method: The get() method allows you to access the value associated with a key. It returns the value if the key is present in the dictionary, and you can also provide a default value to be returned if the key is not found. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

print(my_dict.get('name'))  # Output: John
print(my_dict.get('age'))   # Output: 30
print(my_dict.get('country'))  # Output: None

# Providing a default value
print(my_dict.get('country', 'Unknown'))  # Output: Unknown

Keys() Method: The keys() method returns a view object that contains all the keys in the dictionary. You can convert this view object to a list and then iterate over the keys to access the corresponding values. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

for key in my_dict.keys():
    print(my_dict[key])

Values() Method: The values() method returns a view object that contains all the values in the dictionary. You can convert this view object to a list and directly access the values. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

for value in my_dict.values():
    print(value)

It's important to note that if you try to access a key that does not exist in the dictionary using the square bracket notation ([]), it will raise a KeyError. However, using the get() method allows you to provide a default value or handle the absence of a key gracefully.

Using these methods, you can easily access the values stored in a dictionary based on their corresponding keys.

Related Questions You Might Be Interested