嵌套是什么
将字典储存在列表里面、将列表储存在字典里面,这种称为嵌套
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