Fundamentals of Python Programming
Python dictionary values()
Introduction
In Python, values() is an inbuilt function that returns a view object. It has the values of the dictionary, as a list. Now if we check the type of the return value we will get the “dict_values” object. It needs to be cast to obtain the actual list.
Syntax
Parameters
No parameters are needed.
Returns
Returns a list of all the values available in a given dictionary.
The values have been stored in a reversed manner.
Error
No error is expected because no parameters are required.
Examples
Code 1
Output
Code 2
Output
Python Dictionary get()
If we want to access the value of a key we use the get() method.
Syntax
The Syntax of the get() method is:
Parameters
In the get() method, there are two parameters that the method takes.
key- the key will be searched whose value is to be searched.
value (optional)- If the key is not returned then the value passed will be returned. The default value returned will be None.
Returns
get() method returns:
- If the key is in the dictionary, it will return its value.
- If the key is not found and the value is not specified it will return None.
- If the key is not found and the value is specified then it returns that value.
Examples
Code 1
Output
Code 2
Output
Python get() method Vs dict[key]
The get() method will return a default value that is specified if the key is not found. In the case of dict[key], a key error exception is raised.
Code
Output
Some more examples
Code 1
Output
Code 2
Output
Code 3
Output
Conclusion
- In Python, values() is an inbuilt function that returns a view object. It has the values of the dictionary, as a list.
- The values() returns a list of all the values available in a given dictionary. The values have been stored in a reversed manner.
- If we want to access the value of a key we use the get() method.
- The get() method will return a default value that is specified if the key is not found. In the case of dict[key], a key error exception is raised.