为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印字典的标题?

如何打印字典的标题?

翻翻过去那场雪 2022-09-27 10:51:01
代码ralph = {'type': 'cat','owner': 'mark'}lucy = {'type': 'cat','owner': 'carrie'}pets = [ralph, lucy]for pet in pets:    print(str(pet))    owner = pet['owner']    print('pet type: ' + pet['type'] + '\n' + 'owner: ' + owner.title())提供输出:{'type': 'cat', 'owner': 'mark'}pet type: catowner: Mark{'type': 'cat', 'owner': 'carrie'}pet type: catowner: Carrie我试图打印每只宠物的名字(拉尔夫和露西)
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

您正在尝试访问变量名称。虽然这在原则上是可能的,但您不想这样做。


我假设你正在尝试这样的想法:


pet1 = {'type': 'cat','owner': 'mark', 'name': 'ralph'}

pet2 = {'type': 'cat','owner': 'carrie', 'name': 'lucy'}

pets = [pet1, pet2]


for pet in pets:

    print('pet name: ' + pet['name'])


查看完整回答
反对 回复 2022-09-27
  • 1 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号