Python 字典 len 函数

Python 字典 len 函数用于返回字典的长度(键值对的总数)。在本节中,我们将讨论如何使用此字典 len 函数,其语法如下:

len(dictionary_name)

字典 len 示例

字典 len 函数返回字典的长度。下面的 Python 代码打印 myDict 的长度。

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

print("Dictionary Items: ", myDict)

# Dict length
print("\nThe Dictionary length :  ",  len(myDict))
Dictionary len or length function

在此程序中,我们将向 字典 插入一个新值并检查其长度。接下来,我们更新一个值并显示长度。

myDict = {'name': 'Kevin', 'age': 25}

# Print Total Items
print("Items  :  ",  myDict)
print("The length :  ",  len(myDict))

# Add an Item 
myDict['job'] = 'Programmer'
print("\nItems  :  ",  myDict)
print("The length :  ",  len(myDict))

# Update an Item
myDict['name'] = 'Python'
print("\nItems  :  ",  myDict)
print("The length :  ",  len(myDict))
Items  :   {'name': 'Kevin', 'age': 25}
The length :   2

Items  :   {'name': 'Kevin', 'age': 25, 'job': 'Programmer'}
The length :   3

Items  :   {'name': 'Python', 'age': 25, 'job': 'Programmer'}
The length :   3