知妳网 知妳网-知妳所想,懂妳所需

知妳网

知妳网知你所想为你解忧最懂你的网站

python字典个数统计

1. 统计字典的键值对总数

直接使用 `len` 函数即可获取字典中键的数量(键值对的个数):

python字典个数统计

python

my_dict = {'a': 1, 'b': 2, 'c': 3}

count = len(my_dict)

print(count) 输出: 3

2. 统计字典*定值的出现次数

如果要统计某个值在字典中出现的次数,可以使用 `values` 遍历值并计数:

python

my_dict = {'a': 1, 'b': 2, 'c': 2, 'd': 2}

target_value = 2

方法1: 列表推导式 + count

count = list(my_dict.values).count(target_value)

print(count) 输出: 3

方法2: 使用 collections.Counter

from collections import Counter

value_counts = Counter(my_dict.values)

print(value_counts[2]) 输出: 3

3. 统计嵌套字典的总元素数

如果字典的值是嵌套的字典,可以通过递归统计所有层级元素:

python

def count_nested_dict(d):

count = 0

for value in d.values:

if isinstance(value, dict):

count += count_nested_dict(value)

else:

count += 1

return count

my_dict = {

'a': {'x': 1, 'y': 2},

'b': {'z': {'p': 5, 'q': 6}},

'c': 3

print(count_nested_dict(my_dict)) 输出: 5(1+2+2)

4. 统计所有键、值或键值对的*

如果需要获取键、值或键值对的*,可以使用以下方法:

python

my_dict = {'a': 1, 'b': 2, 'c': 3}

所有键

keys = my_dict.keys

print(len(keys)) 输出: 3

所有值

values = my_dict.values

print(len(values)) 输出: 3

所有键值对(元组形式)

items = my_dict.items

print(len(items)) 输出: 3

  • 基础统计:直接使用 `len(dict)`。
  • 值统计:遍历 `dict.values` 并结合 `Counter` 或 `count`。
  • 嵌套字典:递归遍历所有层级。
  • 根据你的需求选择对应方法即可!