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

如何提升嵌套字典的Python程序代码可读性?

优化Python字典信息打印的几种方法

针对你代码中print语句因大量\n导致可读性差的问题,这里提供几个实用的优化方案:

1. 拆分多个print语句

把每个字段的打印拆分成单独的print调用,代码结构更清晰,一眼就能看出每个字段的输出逻辑:

friend_1 = {
    "first_name": "Tu",
    "last_name": "Le",
    "age": 18,
    "city": "Hanoi"
}

friend_2 = {
    "first_name": "Hao",
    "last_name": "Do",
    "age": 18,
    "city": "Hanoi"
}

friend_3 = {
    "first_name": "Hieu",
    "last_name": "Tran",
    "age": 18,
    "city": "HCMC"
}

friends = [friend_1, friend_2, friend_3]

for friend in friends:
    print(f"\nFirst name: {friend['first_name'].title()}")
    print(f"Last name: {friend['last_name'].title()}")
    print(f"Age: {friend['age']}")
    print(f"City: {friend['city'].title()}")

2. 使用多行f-string(三引号)

利用Python的多行字符串特性,直接按照输出格式编写内容,无需手动添加\n,代码视觉上和最终输出一致,可读性拉满:

# 前面定义friend和friends的代码不变

for friend in friends:
    info = f"""
First name: {friend['first_name'].title()}
Last name: {friend['last_name'].title()}
Age: {friend['age']}
City: {friend['city'].title()}
    """
    print(info.strip())  # strip()去掉字符串首尾的多余换行

3. 提取为格式化函数

如果后续需要多次打印这类信息,或者要调整输出格式,把打印逻辑封装成单独的函数会更易维护:

def print_friend_info(friend):
    print(f"\nFirst name: {friend['first_name'].title()}")
    print(f"Last name: {friend['last_name'].title()}")
    print(f"Age: {friend['age']}")
    print(f"City: {friend['city'].title()}")

# 前面定义friend和friends的代码不变

for friend in friends:
    print_friend_info(friend)

4. 用join拼接字符串列表

把每个字段的字符串存入列表,再用换行符\n拼接后打印,同样能避免大量\n堆积:

# 前面定义friend和friends的代码不变

for friend in friends:
    line_list = [
        f"First name: {friend['first_name'].title()}",
        f"Last name: {friend['last_name'].title()}",
        f"Age: {friend['age']}",
        f"City: {friend['city'].title()}"
    ]
    print("\n" + "\n".join(line_list))

这几种方法都能达到和你原代码一致的输出效果,但代码可读性和可维护性都有明显提升,你可以根据实际场景选择合适的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:45:21