AppDividend
Latest Code Tutorials

Python Dictionary values() Function Example

0

Python dictionary values() is an inbuilt 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.

Python Dictionary values()

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

Syntax

dictionary.values()

The values() does not take any parameter, and it just 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 which contains marks of some students, and we have printed the dictionary.

After that, we have printed all the marks using values() method, and it 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 {}.

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

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.