无涯教程-Python3 - dict.values()函数

104 阅读1分钟

Python values()方法用于从字典中收集所有值。它不带任何参数,并返回值的字典。如果字典没有值,它将返回一个空字典。下面给出了此方法的语法和示例。

dict.values - 语法

values()

dict.values - 返回

它返回值的字典。

这是一个简单的示例,该示例返回字典中的所有值。下面给出一个例子。

# Python dictionary values() Method
# Creating a dictionary
einventory = {Fan: 200, Bulb:150, Led:1000}
# 函数调用
stock = einventory.values()
# 显示结果
print("Stock available",einventory)

输出

Stock available {Fan: 200, Bulb: 150, Led: 1000}

如果字典已经为空,则此方法还返回一个空字典,但没有错误或异常。请参见下面的示例。

# Python dictionary values() Method
# Creating a dictionary
einventory = {}
# 函数调用
stock = einventory.values()
# 显示结果
print("Stock available",einventory)

输出

Stock available {}

本示例使用各种方法来获取有关字典的信息,例如长度,键等。

# Python dictionary values() Method
# Creating a dictionary
einventory = {Fan: 200, Bulb:150, Led:1000}
# Applying functions
length = len(einventory)
print("Total number of values:",length)
keys = einventory.keys()
print("All the Keys:",keys)
item = einventory.items()
print("Items:",einventory)
p = einventory.popitem()
print("Deleted items:",p)
stock = einventory.values()
print("Stock available",einventory)

输出

Total number of values: 3
All the Keys: dict_keys([Fan, Bulb, Led])
Items: {Fan: 200, Bulb: 150, Led: 1000}
Deleted items: (Led, 1000)
Stock available {Fan: 200, Bulb: 150}

参考链接

www.learnfk.com/python3/pyt…