Python字典值含大括号问题:如何移除大括号获取纯数字值?
问题描述
编写了一个接收短语或句子的函数,目标是输出以单词为键、字符数为对应值的字典。但调用wordcount('hello my name is bobby')时,返回结果为{'hello': {5}, 'my': {2}, 'name': {4}, 'is': {2}, 'bobby': {5}},值带有大括号(集合格式),希望返回{'hello':5, 'my':2, 'name':4, 'is':2, 'bobby':5},尝试多种方法未解决。代码如下:
def wordcount(text): from collections import defaultdict d = defaultdict(set) for word in text.split(): d[word].add(len(word)) return {a :b for a, b in d.items()}
问题原因与解决方法
问题根源
你用了defaultdict(set)初始化字典,这意味着每个键对应的默认值是集合(set),后续调用d[word].add(len(word))是把单词长度添加到集合里,最终返回的字典值自然是集合类型(表现为带大括号的格式)。
修改方案
不需要用集合类型,直接给键赋值为单词的长度即可,下面是两种简洁的修改方式:
方式一:使用普通字典(最直接)
def wordcount(text): word_dict = {} for word in text.split(): word_dict[word] = len(word) return word_dict
方式二:保留defaultdict(若习惯用该工具)
如果一定要用defaultdict,可以把默认类型改成int,但其实这里不需要默认值特性,直接赋值即可:
from collections import defaultdict def wordcount(text): d = defaultdict(int) for word in text.split(): d[word] = len(word) # 直接赋值,而非add操作 return dict(d)
调用修改后的函数,就能得到你期望的{'hello':5, 'my':2, 'name':4, 'is':2, 'bobby':5}结果。
内容的提问来源于stack exchange,提问作者tiredofcoding
相关产品推荐
相关产品推荐

