You need to enable JavaScript to run this app. Python字典遍历:访问键对应列表值并格式化输出人员信息
优惠活动
大模型
产品
解决方案
定价
更多

Python字典遍历:访问键对应列表值并格式化输出人员信息

实现方法

你可以通过以下步骤完成需求,全程可以用你已经熟悉的f-string完成格式化:

  • 遍历字典时调用items()方法,循环中可以同时拿到人员姓名(字典的键)和对应的属性列表(字典的值),无需额外通过键索引取值
  • 对拿到的属性列表,既可以通过下标索引读取每个元素,也可以直接通过序列解包把两个元素拆成独立变量,写法更简洁
  • 将变量传入f-string拼接目标语句,根据需求选择print()或者sys.stderr.write()输出即可

基础print输出版本

people = {"Jenn" : ['renter', 'large room'], 
          "Lana" : ['renter', 'small room'], 
          "Ricky" :['owner', 'large room']
          }

for name, attr_list in people.items():
    # 方式1:序列解包拆分列表元素
    role, room_type = attr_list
    # 等价的索引取值写法,效果完全一致:
    # role = attr_list[0]
    # room_type = attr_list[1]
    print(f"{name} is the {role} of a {room_type}.")

注意:你给出的预期输出中"Rickey"存在拼写笔误,和字典里存储的键Ricky不匹配,代码实际运行后第三行输出为Ricky is the owner of a large room.,如果需要完全匹配预期文本,把字典里的键修改为Rickey即可。

sys.stderr.write 输出版本

该方法不会像print()一样自动在字符串末尾补充换行符,需要手动在f-string末尾加上\n,否则所有输出会挤在同一行:

import sys

people = {"Jenn" : ['renter', 'large room'], 
          "Lana" : ['renter', 'small room'], 
          "Ricky" :['owner', 'large room']
          }

for name, attr_list in people.items():
    role, room_type = attr_list
    sys.stderr.write(f"{name} is the {role} of a {room_type}.\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 13:24:01