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

Python怎么修改字典输出格式,去掉大括号改为自定义的每行键值对形式?

代码修改方案

你现有代码存在两处需要调整的地方:

  1. 传参变量名错误:你把用户输入存储到了sent变量中,但调用word_count时传入了未定义的变量q,运行会直接报错
  2. 缺少自定义格式输出逻辑:原有代码只返回了词频字典,没有按要求逐行输出的逻辑

修改后完整代码

def word_count(q):
    i = dict()
    j = q.split()
    j.sort()
    for word in j:
        if word in i:
            i[word] += 1
        else:
            i[word] = 1
    return i

sent = input().lower()
x = word_count(sent)
# 新增格式化输出逻辑
for word, count in x.items():
    print(f"{word} : {count}")

运行效果

输入hello i am时,输出完全符合你的预期:

am : 1
hello : 1
i : 1

可选优化:如果不需要保留原有计数逻辑的写法,可以用Python内置的collections.Counter简化代码,最终输出效果一致:

from collections import Counter
sent = input().lower()
# 直接统计+按字母排序
word_counts = sorted(Counter(sent.split()).items())
for word, count in word_counts:
    print(f"{word} : {count}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:54:05