在学习过程中遇到了很多小麻烦,所以将字典列表的循环嵌套问题,进行了个浅浅的总结分类。
首先明确:
p={'name':'lin','age':21}
y={'name':'xue','age':20}
c=[p,y]
print(c)
输出结果: [{'name': 'Jonh', 'age': 18}, {'name': 'Marry', 'age': 19}]
print(f"person's name is {people[0].get('name')}")
print(f"{people[1].get('name')}'s age is {people[1].get('age')}")
#先用person[0/1]访问列表里的元素(字典),再用get方法访问字典里的值
输出结果:
person's name is Jonh Marry's age is 19
for person in people:
#将列表中的字典,依次赋值给person
print(f"{person['name']}'s age is {person['age']}")
#取出每个循环里变量person(字典)的键和值
输出结果:
Jonh's age is 18 Marry's age is 19
因为字典中有多个键值对,所以进行多层嵌套。
外层嵌套访问列表中的每个字典,内层嵌套访问每个字典元素的键值对。
for person in people:
#在每个遍历的字典里再进行嵌套(内层循环)
for k,v in person.items():
print(f"{k}:{v}")
输出结果:
name:Jonh age:18 name:Marry age:19
先用list[索引]访问列表中的元素,用dict[key]方法访问字典中的值。
favourite_places={
'lin':['beijing','tianjin'],
'jing':['chengdu','leshan'],
'huang':['shenzhen']
}
#访问字典中的值可以用:dict_name[key]
print(favourite_places['lin'])
#访问列表里面的元素用索引:list_name[索引]
print(favourite_places['lin'][0].title())
输出结果:
['beijing', 'tianjin'] Beijing
循环访问字典中列表的元素,也是要用dict_name[key]先访问字典中的值(列表)
for i in favourite_places['lin']:
print(i.title())
输出结果:
Beijing Tianjin
注意:直接访问字典中的值,会以列表的形式呈现。
for name,place in favourite_places.items():
print(f"{name.title()}'s favourite places are {place}")
输出结果:
Lin's favourite places are ['beijing', 'tianjin'] Jing's favourite places are ['chengdu', 'leshan'] Huang's favourite places are ['shenzhen']
为了避免,要进行循环嵌套
for names,places in favourite_places.items(): #对三个键值对先进行一个大循环
print(f'{names.title()} favourite places are:') #在大循环里每一组键值对开头先打印这句话
for place in places: #之后再对值进行一个小循环,打印出值中的每个元素
print(place.title())
输出结果:
Lin favourite places are: Beijing Tianjin Jing favourite places are: Chengdu Leshan Huang favourite places are: Shenzhen
p={'name':'lin','age':21}
y={'name':'xue','age':20}
c={p,y}
print(c)
TypeError Traceback (most recent call last)
in
1 p={'name':'lin','age':21}
2 y={'name':'xue','age':20}
----> 3 c={p,y}
4 print(c)
TypeError: unhashable type: 'dict'
users={
'a':{'name':'lin','age':21},
'b':{'name':'xue','age':20}
}
print('-----------直接访问输出-------------------')
print(users['a']['name'],users['a']['age'])
print(users['b']['name'],users['b']['age'])
print('\n-----------循环嵌套的方法输出-------------------')
for username,userinfo in users.items():
print('\n'+username+':')
for name,age in userinfo.items():
print(name,age)
输出结果:
-----------直接访问输出------------------- lin 21 xue 20 -----------循环嵌套的方法输出------------------- a: name lin age 21 b: name xue age 20