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

Python3如何按指定格式打印嵌套字典?

解决嵌套字典的自定义打印格式问题

嗨,我来帮你搞定这个嵌套字典的打印格式问题~你之前的代码直接打印内层字典时,Python会默认输出它的原生字符串格式(带大括号),所以咱们需要手动处理内层的键值对,把它们转换成你想要的样式。

方法一:列表推导式 + 字符串拼接

直接遍历外层字典的每个文档,然后把内层的单词和计数转换成指定格式,再用分号连接起来:

dictionary = {'Doc1': {'word1': 3, 'word2': 1}, 'Doc2': {'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3': {'word1': 2}}

for doc_name, word_counts in dictionary.items():
    # 将内层字典的键值对转为 "单词:计数" 格式的字符串列表
    word_strings = [f"{word}:{count}" for word, count in word_counts.items()]
    # 用 "; " 把所有单词字符串连接成一个整体
    formatted_content = "; ".join(word_strings)
    # 打印最终格式
    print(f"{doc_name}: {formatted_content}")

方法二:更简洁的生成器表达式写法

如果不想创建额外的列表,可以用生成器表达式代替列表推导式,内存占用会更优:

dictionary = {'Doc1': {'word1': 3, 'word2': 1}, 'Doc2': {'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3': {'word1': 2}}

for doc_name, word_counts in dictionary.items():
    formatted_content = "; ".join(f"{w}:{c}" for w, c in word_counts.items())
    print(f"{doc_name}: {formatted_content}")

输出结果

运行上面的代码后,你会得到完全符合需求的输出:

Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3:3
Doc3: word1:2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:40:25