Python字典 |值()
values()是Python编程语言中的一个内置方法,它返回一个视图对象。视图对象包含字典的值,作为一个列表。如果对返回值使用 type() 方法,则会得到“dict_values 对象”。必须强制转换才能获得实际列表。
句法:
dictionary_name.values()
参数:
没有参数
回报:
returns a list of all the values available in a given dictionary.
the values have been stored in a reversed manner.
错误:
As we are not passing any parameters there
is no scope for any error.
代码#1:
# Python3 program for illustration
# of values() method of dictionary
# numerical values
dictionary = {"raj": 2, "striver": 3, "vikram": 4}
print(dictionary.values())
# string values
dictionary = {"geeks": "5", "for": "3", "Geeks": "5"}
print(dictionary.values())
输出:
dict_values([2, 3, 4])
dict_values(['5', '3', '5'])
实际应用:
给定姓名和薪水,返回所有员工的总薪水。
代码#2:
# Python3 program for illustration
# of values() method in finding total salary
# stores name and corresponding salaries
salary = {"raj" : 50000, "striver" : 60000, "vikram" : 5000}
# stores the salaries only
list1 = salary.values()
print(sum(list1)) # prints the sum of all salaries
输出:
115000