如何打印字典的标题?

代码


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: cat

owner: Mark

{'type': 'cat', 'owner': 'carrie'}

pet type: cat

owner: Carrie

我试图打印每只宠物的名字(拉尔夫和露西)


翻翻过去那场雪
浏览 112回答 1
1回答

慕哥6287543

您正在尝试访问变量名称。虽然这在原则上是可能的,但您不想这样做。我假设你正在尝试这样的想法: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'])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python