9. 嵌套

嵌套是什么

将字典储存在列表里面、将列表储存在字典里面,这种称为嵌套

1 在列表中存储字典

houses_0={'name':'Gryffindor',
		  'representation':'lion',
		  'color':'red'}

houses_1={'name':'Slytherin',
		  'representation':'snake',
		  'color':'green'}

houses_2={'name':'Hufflepuff',
		  'representation':'badger',
		  'color':'yellow'}

houses_3={'name':'Ravenclaw',
		  'representation':'eagle',
		  'color':'blue'}

houses=[houses_0,houses_1,houses_2,houses_3]

for house in houses:
	print(house)
----------
{'name': 'Gryffindor', 'representation': 'lion', 'color': 'red'}
{'name': 'Slytherin', 'representation': 'snake', 'color': 'green'}
{'name': 'Hufflepuff', 'representation': 'badger', 'color': 'yellow'}
{'name': 'Ravenclaw', 'representation': 'eagle', 'color': 'blue'}

2 在字典中存储列表

school={'name':'Hogwarts',
		'houses':['Gryffindor','Hufflepuff','Slytherin','Ravenclaw']}

for house in school['houses']:
	print(f"British magic shcool is {school['name']},{house} is one of {school['name']}'s houses")
----------
British magic shcool is Hogwarts,Gryffindor is one of Hogwarts's houses
British magic shcool is Hogwarts,Hufflepuff is one of Hogwarts's houses
British magic shcool is Hogwarts,Slytherin is one of Hogwarts's houses
British magic shcool is Hogwarts,Ravenclaw is one of Hogwarts's houses

3 在字典中存储字典

houses={'Gryffindor':{'representation':'lion',
					  'color':'red'},
		'Slytherin' :{'representation':'snack',
					  'color':'green'},
		'Hufflepuff':{'representation':'badger',
					  'color':'yellow'},
		'Ravenclaw':{'representation':'eagle',
					  'color':'blue'}
		}


for house_name,inform in houses.items():
	print(f'{house_name}的基本信息为:')
	print(f"代表动物为{inform['representation']},代表颜色为{inform['color']}")
----------
Gryffindor的基本信息为:
代表动物为lion,代表颜色为red
Slytherin的基本信息为:
代表动物为snack,代表颜色为green
Hufflepuff的基本信息为:
代表动物为badger,代表颜色为yellow
Ravenclaw的基本信息为:
代表动物为eagle,代表颜色为blue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值