The values()
method in Python is a built-in method that is used to retrieve the values from a dictionary. This method returns a view of all the values in the dictionary, and does not modify the original dictionary. You can use the values returned by this method for various purposes such as data analysis, looping, etc.
Syntax
dict.values()
Parameters
The values()
method does not take any parameters.
Examples
Example 1: Retrieving Values from a Dictionary
Consider the following example, where we retrieve the values from a dictionary:
student = {'name': 'John', 'age': 25, 'gender': 'Male'} values = student.values() print(values)
In this example, we have created a dictionary called student
, which contains the key-value pairs of a student. Then, we use the values()
method to retrieve all the values from the dictionary and store it in a variable called values
. The final output, which we print, will be:
dict_values(['John', 25, 'Male'])
As you can see, the values of the keys ‘name’, ‘age’, and ‘gender’ have been retrieved and stored in the values
variable. Note that the values are stored in a dict_values
object, which is a view of the values in the original dictionary.
Example 2: Using the Values in a Loop
Consider the following example, where we use the values from a dictionary in a loop:
student = {'name': 'John', 'age': 25, 'gender': 'Male'} for value in student.values(): print(value)
In this example, we have created a dictionary called student
, which contains the key-value pairs of a student. Then, we use the values()
method to retrieve all the values from the dictionary and use it in a loop. The final output, which we print, will be:
John 25 Male
As you can see, the values of the keys ‘name’, ‘age’, and ‘gender’ have been retrieved and printed in the loop.
Example 3: Counting the Occurrence of Values
Consider the following example, where we count the occurrence of values in a dictionary:
student_grades = {'John': 75, 'Jane': 89, 'Jim': 75} grade_count = {} for grade in student_grades.values(): if grade in grade_count: grade_count[grade] += 1 else: grade_count[grade] = 1 print(grade_count)
In this example, we have created a dictionary called student_grades
, which contains the names of students as keys and their grades as values. Then, we use the values()
method to retrieve all the grades from the dictionary and use it to count the occurrence of each grade. The final output, which we print, will be:
{75: 2, 89: 1}
As you can see, the grades 75 and 89 have been counted, and the output shows that the grade 75 has occurred 2 times and the grade 89 has occurred 1 time in the dictionary.
In conclusion, the values()
method in Python is a useful method that allows you to retrieve the values from a dictionary and use it for various purposes. Whether it be for data analysis, looping, or counting the occurrence of values, the values()
method is a useful tool for working with dictionaries in Python.