如何在Python中计算一个字典中的键的数量

2,188 阅读1分钟

在 Python 中得到一个字典的长度,使用len() 方法。dict.keys()是一个内置的Python方法,返回一个视图对象。

Python 中的字典计数

计算 Python 字典中的键数,可以使用len() 函数。该 len()是一个内置的函数,可以在像字典一样的迭代器中使用,并返回字典中键值对的数量,这就是键值数量的精确计数。

dict = {
 "name": "Millie",
 "character": "Eleven",
 "show": "Strange Things",
}

output = len(dict)
print(output)

output_2 = len(dict.keys())
print(output_2)

输出

3
3

你可以看到 key 和 key-value 对的计数是一样的,都是 3。这是因为**dict.keys()**函数是一个内置的方法,它返回一个视图对象,按插入的顺序显示字典中所有 key 的列表。

检查 dictionary 的计数是否为 0

要在Python 中检查一个dictionary计数是否为 0,使用len() 函数,用 double equals 操作符将其结果与0比较。

dict = {}

if len(dict) == 0:
  print('The dict is empty')
else:
  print('The dict is not empty')

输出

The dict is empty

你可以看到,如果 dictionary 的长度是 0,那么这个 dictionary 是空的。

你也可以用 Python中的not 操作符 来检查 dictionary 是否为空。

dict = {}

if not dict:
  print('The dict is empty')
else:
  print('The dict is not empty')

输出

The dict is empty

本教程就到此为止。

相关文章

Python 集合长度

Python元组的长度

列表的长度

Python数组长度

Python字符串的长度