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

使用标准方法按值排序字典报错:TypeError: 'dict'对象不可调用

问题解决:TypeError: 'dict' object is not callable

错误原因

你把变量名命名成了sorted,而sorted是Python的内置函数,这就导致执行dict(sorted(...))时,这里的sorted已经被你赋值的字典覆盖,不再是原本的排序函数,自然会报错“字典对象不可调用”。

修复代码

只需要把变量名改成非内置函数名即可,比如改成sorted_positive_counts:

word_counts = {'positive': {},
                'neutral': {},
                'negative': {}}

for idx, sentence in enumerate(df_norm['Full Text']):
    for word in sentence:
        sentiment = df_norm['Sentiment'][idx]
        if word in word_counts[sentiment]:
            word_counts[sentiment][word] += 1
        else:
            word_counts[sentiment][word] = 1

# 更换变量名,避免覆盖内置函数
sorted_positive_counts = dict(sorted(word_counts['positive'].items(), key=lambda x: x[1]))
print(sorted_positive_counts)

顺便优化了两处代码细节:

  • 把重复调用的df_norm['Sentiment'][idx]提取为变量sentiment,提升代码可读性和执行效率
  • 去掉了冗余的.keys()判断,直接用if word in 字典即可完成成员检查

内容的提问来源于stack exchange,提问作者jack gell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:40:29