AppDividend
Latest Code Tutorials

Python Dictionary values: The Complete Guide

Python dict values() method returns the view object that displays a list of all the values in the dictionary.

Python Dictionary values()

Python dictionary values() is a built-in function that returns a list of all the values available in a given dictionary. The values() method returns a view object that displays a list of all the values in the dictionary. The values() method doesn’t take any parameters.

Syntax

dictionary.values()

The values(do not take any parameters returns values.

Return values

The values() method returns a view object which contains a list of values of each key.

Programming example

# app.py

# Declaring dictionary
student_marks = {'Debasis': 89, 'Shouvik': 97, 'Rohit': 74, 'Shubh': 76}
# printing the dictionay
print(student_marks)
# Printing values of all keys
print(student_marks.values())
# printing total marks of all students
print(sum(student_marks.values()))

Output

{'Debasis': 89, 'Shouvik': 97, 'Rohit': 74, 'Shubh': 76}
dict_values([89, 97, 74, 76])
336

In the above program, we have declared a dictionary containing some students’ marks, and we have printed the dictionary.

After that, we have printed all the marks using the g values() method, which returns a list of marks. After that, we have printed the sum of all the marks of all students.

How values() works when a dictionary is modified

See the following code.

# app.py

apps = { 'facebook': 1, 'instagram': 2, 'messenger': 3 }

values = apps.values()
print('Original items:', values)

# delete an item from dictionary
del[apps['messenger']]
print('Updated items:', values)

Output

pyt python3 app.py
Original items: dict_values([1, 2, 3])
Updated items: dict_values([1, 2])

Conclusion

Python’s efficient key/value hash table structure is called a “dict”. The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, … }. The “empty dict” is just an empty pair of curly braces {}.

The dict values() method returns a view object that displays a list of all the values in the dictionary.

That’s it for this tutorial.

See also

Python dictionary setDefault()

Python dictionary popitem()

Python dictionary items()

Python dictionary fromKeys()

Python dictionary keys()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.