Sometimes we need to get a list of all of the values only (without keys) from a Python dictionary.
Suppose we have a dictionary numbers defined as follows:
numbers = dict() numbers["a"] = 1 numbers["b"] = 2 numbers["c"] = 3 numbers["d"] = 4
To return a list of just the values at all of the keys from this data structure, we can use the values method.
Note that the output needs to be converted to a regular list.
result = list(numbers.values())
The result is:
[1, 2, 3, 4]
Another option is to use a list comprehension. This is especially useful if we want to do some further computations on all of the values immediately.
result = [numbers[key] for key in numbers.keys()]
The result is:
[1, 2, 3, 4]
The built-in function keys() returns all keys in the dictionary.
Then, numbers[key] is called for each key to get the value at that key.
Finally, the list comprehension results in a list of all values.