Skip to main content

How to access values in a dictionary in Python

How to access values in a dictionary in Python.

Here is a step-by-step tutorial on how to access values in a dictionary in Python:

  1. First, you need to understand what a dictionary is in Python. A dictionary is an unordered collection of key-value pairs, where each key is unique.

  2. To access a value in a dictionary, you can use the key associated with that value. The key serves as an identifier and allows you to retrieve the corresponding value.

  3. Let's start by creating a dictionary in Python. You can create a dictionary by enclosing key-value pairs in curly braces {}. For example, let's create a dictionary called my_dict with some sample data:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
  1. Now that we have our dictionary, we can access the values using their respective keys. To access a value, you can use square brackets [] and provide the key inside them. For example, to access the value associated with the key 'name', you can write:
name_value = my_dict['name']
print(name_value) # Output: John
  1. You can also directly use the key to access the value without assigning it to a separate variable. For example:
print(my_dict['age'])  # Output: 25
  1. It's important to note that if you try to access a key that doesn't exist in the dictionary, it will raise a KeyError. To avoid this, you can use the get() method, which returns None (or a default value you specify) instead of raising an error. For example:
print(my_dict.get('city'))  # Output: New York
print(my_dict.get('occupation')) # Output: None
  1. If you want to provide a default value instead of None, you can pass it as the second argument to the get() method. For example:
print(my_dict.get('occupation', 'Unknown'))  # Output: Unknown
  1. Another way to access values in a dictionary is by using the values() method. This method returns a view object that contains all the values in the dictionary. You can convert this view object into a list to access the values individually. For example:
values_list = list(my_dict.values())
print(values_list) # Output: ['John', 25, 'New York']
  1. If you want to access both the keys and values simultaneously, you can use the items() method. This method returns a view object that contains tuples of key-value pairs. Again, you can convert this view object into a list to access the pairs individually. For example:
items_list = list(my_dict.items())
print(items_list) # Output: [('name', 'John'), ('age', 25), ('city', 'New York')]

That's it! You now know how to access values in a dictionary in Python. Remember to use the key associated with the value you want to retrieve and make use of the methods like get(), values(), and items() to access values in different ways.