笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册
查看: 4879|回复: 1

[问题求助] 列表嵌套字典问题

[复制链接]

新手上路

Rank: 1

积分
3
发表于 2022-3-7 11:25:07 | 显示全部楼层 |阅读模式
kitty = {'species':'cat',
         'owner':'Lucy'}
tide = {'species':'bear',
         'owner':'Jim'}
black = {'species':'dog',
         'owner':'owen'}
woody = {'species':'bird',
         'owner':'Li Lei'}
pets =[kitty,tide,black,woody]
for pet in pets:
      for sp ,ow in pet.items():
        print ('\nspecies: '+ pet['species'])
        print ('owner: '+ pet['owner'])
   

运行出来:
species: cat
owner: Lucy

species: cat
owner: Lucy

species: bear
owner: Jim

species: bear
owner: Jim

species: dog
owner: owen

species: dog
owner: owen

species: bird
owner: Li Lei

species: bird
owner: Li Lei


问题一:为什么每一个字典都打印了两次?我该怎样修改。
问题二:我想在每一个字典前面打印出列表名,该怎样做
我知道答案 回答被采纳将会获得10 C币 已有1人回答
回复

使用道具 举报

新手上路

Rank: 1

积分
9
发表于 2022-3-7 11:26:03 | 显示全部楼层
你字典有2对键值,循环2次,第二个循环不要就行了
你打印哪个列表名
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 09:55 , Processed in 0.025396 second(s), 22 queries .

© 2001-2020

快速回复 返回顶部 返回列表