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
dictionary_name.values() |
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
dictionary = {"A": 3, "B": 2, "C": 3} |
Output
dict_values([3, 2, 3]) |
Code 2
s = {"A" : 1, "B" : 2, "C" : 3} |
Output
6 |
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:
dict.get(key[, value]) |
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
marks = {'A1':67, 'A2':87} |
Output
67 |
Code 2
p = {'Name': 'Akash', 'Age': 18} |
Output
Name: Akash |
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
p = {} |
Output
File "main.py", line 3, in <module> |
Some more examples
Code 1
Cars = { |
Output
dict_values(['Audi', 'A7', 2018]) |
Code 2
Student = { |
Output
dict_values(['Ayush', '614-A', 2018, 4392]) |
Code 3
Staff = { |
Output
Ankush |
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.