Python dictionary allows you to store data in a key-value pair format.
You can extract all values from a dictionary using yourdict.values()
in Python.
Basic Example
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.values()
Output
dict_values([1, 2, 3, 4])
This tutorial teaches you the different methods to extract all values from a dictionary.
Table of Contents
Extract All Values From Dictionary
You can use the values()
method to extract all values from a dictionary.
It returns a new view of the dictionary’s values.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.values()
Output
dict_values([1, 2, 3, 4])
Extract Specific Value From Dictionary
To extract a specific value from the dictionary in Python, use the get() method available in the dictionary class.
- To extract the specific value, you need to know its key already.
The advantage of using the get() method over using dict[] is you can pass the default value to be returned when the key is unavailable in the dictionary.
Code
The following code demonstrates how to get a specific value from a dictionary by using its key.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.get("one", 1)
Output
1
Extract Value from Dictionary By Key
You can extract a value from the dictionary by key using the get()
method.
You need to know the key beforehand.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.get("one", 1)
Output
1
Extract All Values from Dictionary Using Keys
To extract all values from the dictionary using keys:
- Get all the keys from the dictionary using the
keys()
method - Iterate over the keys using the
for
loop
Code
The following code demonstrates how to extract all values from the dictionary using its keys.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
your_list = []
for key in yourdict.keys():
print(yourdict.get(key))
Output
1
2
3
4
Extract Values in a Sorted Order
To extract the values in a sorted order,
- pass the values() to the sorted() function.
- The
sorted()
function returns a new sorted list from the items in the dictionary values list.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
your_list = []
for val in sorted(yourdict.values()):
print(val)
Output
1
2
3
4