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:
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
print(dictionary)
{'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.
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
values = dictionary.values()
print(values)
dict_values(['value1', 'value2', 'value3'])
You can convert this dictionary view object to a list by using the list()
function.
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
values = dictionary.values()
values_list = list(values)
print(values_list)
['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.
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
value = dictionary.get("key1")
print(value)
value1
If the key you pass in does not exist in the dictionary, the get()
method will return None
.
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
value = dictionary.get("key4")
print(value)
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:
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
value = dictionary["key1"]
print(value)
value1
If the key you pass in does not exist in the dictionary, you will get a KeyError
.
dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
value = dictionary["key4"]
print(value)
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!