How to Get Values from a Dictionary in Python

Updated onbyAlan Morel
How to Get Values from a Dictionary in Python

A dictionary in Python is very useful because it allows you to store data in a key-value pair.

After you define a dictionary and add values to it, you will need to later on access them.

In this post, we'll learn how to access the values of a dictionary in Python.

How to get All Values from a Dictionary in Python

To start, let's first define a dictionary:

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } print(dictionary)
BASH
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

If you want to access all the values in a dictionary, you can use the values() method.

This will return a dictionary view object that contains all the values in the dictionary.

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } values = dictionary.values() print(values)
BASH
dict_values(['value1', 'value2', 'value3'])

You can convert this dictionary view object to a list by using the list() function.

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } values = dictionary.values() values_list = list(values) print(values_list)
BASH
['value1', 'value2', 'value3']

How to get a specific Value from a Dictionary using the get() method

If you want to access a specific value in a dictionary, you can use the get() method.

This method takes in a key as a parameter and returns the value associated with that key.

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } value = dictionary.get("key1") print(value)
BASH
value1

If the key you pass in does not exist in the dictionary, the get() method will return None.

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } value = dictionary.get("key4") print(value)
BASH
None

How to get a specific Value from a Dictionary using the [] operator

Another way to access a specific value in a dictionary is by using the [] operator.

This operator takes in the key you want to get the value for:

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } value = dictionary["key1"] print(value)
BASH
value1

If the key you pass in does not exist in the dictionary, you will get a KeyError.

PYTHON
dictionary = { "key1": "value1", "key2": "value2", "key3": "value3" } value = dictionary["key4"] print(value)
BASH
KeyError: 'key4'

Conclusion

In this post, we learned how to access the values of a dictionary in Python.

If you want to get all the values in a dictionary, you can use the values() method.

If you want to get a specific value in a dictionary, you can use the get() method or the [] operator.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.