How to Retrieve a Value from a Dictionary in Python?

Estimated read time 2 min read

To retrieve a value from a dictionary in Python, you can use indexing or the get() method. Here’s an example:

# Create a sample dictionary
data = {'A': 1, 'B': 2, 'C': 3}

# Retrieve a value using indexing
value = data['B']
print(value)  # Output: 2

# Retrieve a value using the get() method
value = data.get('C')
print(value)  # Output: 3

In this example, we create a sample dictionary data with key-value pairs.

To retrieve a value from the dictionary:

  • Using indexing: You can directly access a value by specifying the corresponding key as the index inside square brackets, such as data['B']. This retrieves the value associated with the key 'B'.
  • Using the get() method: The get() method allows you to retrieve a value by specifying the corresponding key as an argument, such as data.get('C'). This retrieves the value associated with the key 'C'.

Both approaches will retrieve the value associated with the specified key from the dictionary. The difference is that using indexing raises a KeyError if the key is not found in the dictionary, whereas the get() method returns None (or a default value specified as the second argument) if the key is not found.

Choose the appropriate method based on whether you want to handle the case when the key is not found in the dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply