You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:39:40