如何编写Python代码实现字典值到字符计数字典的转换?
实现Python字典值的字符计数转换
给定原字典:
x = {1: "datascience", 2: "Machine learning", 3: "Pythone"}
需要将其转换为每个键对应字符串的字符出现次数字典,以下是两种实用实现方式:
方法一:手动遍历统计
手动遍历每个字符串的字符,逐个计数并构建新字典:
x = {1: "datascience", 2: "Machine learning", 3: "Pythone"} result = {} for key, s in x.items(): char_count = {} for char in s: # 若不需要统计空格则保留此行,需统计则删除 if char == ' ': continue if char in char_count: char_count[char] += 1 else: char_count[char] = 1 result[key] = char_count print(result)
运行输出示例:
{1: {'d': 1, 'a': 2, 't': 1, 's': 1, 'c': 2, 'i': 1, 'e': 2, 'n': 1}, 2: {'M': 1, 'a': 2, 'c': 1, 'h': 1, 'i': 2, 'n': 2, 'e': 2, 'l': 1, 'r': 1, 'g': 1}, 3: {'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1, 'e': 1}}
方法二:使用collections.Counter(更简洁)
Python标准库的collections.Counter可直接统计可迭代对象的元素出现次数,用它能大幅简化代码:
from collections import Counter x = {1: "datascience", 2: "Machine learning", 3: "Pythone"} result = {} for key, s in x.items(): # 过滤空格后统计,无需过滤则直接用dict(Counter(s)) filtered_chars = [c for c in s if c != ' '] result[key] = dict(Counter(filtered_chars)) print(result)
这段代码和方法一输出结果一致,且代码更简洁高效,适合快速实现需求。
内容的提问来源于stack exchange,提问作者Arun VR
相关产品推荐
相关产品推荐

