在學習程序中遇到了很多小麻煩,所以將字典串列的回圈嵌套問題,進行了個淺淺的總結分類,
- 串列中存盤字典
- 字典中存盤串列
- 字典中存盤字典
- 易錯點
首先明確:
-
1.串列中存盤字典:
-
①串列中存盤多個字典
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
2.字典中存盤串列
①訪問字典中的串列元素
先用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
3.字典中存盤字典
①字典中不能全部由字典元素組成,會報錯,
p={'name':'lin','age':21}
y={'name':'xue','age':20}
c={p,y}
print(c)
TypeError Traceback (most recent call last)
<ipython-input-46-4127ab9ea962> in <module>
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
4.容易出的小錯誤:
①訪問順序:
②字典的值為串列,訪問的結果是輸出整個串列
③字典中不能全部由字典元素組成
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357116.html
標籤:python
上一篇:《JavaScript百煉成仙》統一回復粉絲們的一些問題
下一篇:PyCharm插件和配置
