在 Python 中要计算一个 dictionary 有多少个元素 (键值对) ,可以使用len()方法。
Python 字典的长度
要在Python 中得到一个字典的长度,使用**len()**方法。 len()是一个内置的Python方法,可以得到字典中键值对的数量。
dict = {
"name": "Millie",
"character": "Eleven",
"show": "Strange Things",
}
print("The length of a dictionary is:", len(dict))
输出
The length of a dictionary is: 3
你可以看到 dictionary 有三个 key-value 对,这就是为什么它返回三个作为输出。
使用 len() 函数检查 dictionary 是否为空
要检查一个dictionary是否为空,使用len() 函数,并使用 double equals 操作符(==) 对0进行检查。
dict = {}
if len(dict) == 0:
print("Dictionary is empty")
else:
print("Dictionary is not empty")
输出结果
Dictionary is empty
你可以看到 dictionary 是空的,并且通过与 0 的比较给出了正确的输出。
本教程到此结束。