欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中字典和列表的相互嵌套問題詳解

 更新時間:2021年11月15日 11:43:19   作者:Wanster  
這篇文章主要為大家詳細介紹了python中字典和列表相互嵌套的問題,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

首先明確:

1.訪問字典中的元素:dict_name[key] / dict_name.get(key)

2.訪問列表中的元素:list_name[索引]

1.列表中存儲字典:

1.列表中存儲多個字典

p={'name':'lin','age':21}
y={'name':'xue','age':20}
c=[p,y]
print(c)

輸出結(jié)果:

[{'name': 'Jonh', 'age': 18}, {'name': 'Marry', 'age': 19}]

2.訪問列表中字典的值

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方法訪問字典里的值

輸出結(jié)果:

person's name is Jonh
Marry's age is 19

3.遍歷訪問多個值

for person in people:                                            
#將列表中的字典,依次賦值給person                       
    print(f"{person['name']}'s age is {person['age']}")          
    #取出每個循環(huán)里變量person(字典)的鍵和值

輸出結(jié)果:

Jonh's age is 18
Marry's age is 19

因為字典中有多個鍵值對,所以進行多層嵌套。

外層嵌套訪問列表中的每個字典,內(nèi)層嵌套訪問每個字典元素的鍵值對。

for person in people:    
    #在每個遍歷的字典里再進行嵌套(內(nèi)層循環(huán))
    for k,v in person.items():          
        print(f"{k}:{v}")

輸出結(jié)果:

name:Jonh
age:18
name:Marry
age:19name:Jonh
age:18
name:Marry
age:19

2.字典中存儲列表

1.訪問字典中的列表元素

先用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())

輸出結(jié)果:

['beijing', 'tianjin']
Beijing

循環(huán)訪問字典中列表的元素,也是要用dict_name[key]先訪問字典中的值(列表)

for i in favourite_places['lin']:     
    print(i.title())

輸出結(jié)果:

Beijing
Tianjin

2.訪問字典中的值(字典中的值為列表)

注意:直接訪問字典中的值,會以列表的形式呈現(xiàn)。

for name,place in favourite_places.items():
    print(f"{name.title()}'s favourite places are {place}")

 輸出結(jié)果:

Lin's favourite places are ['beijing', 'tianjin']
Jing's favourite places are ['chengdu', 'leshan']
Huang's favourite places are ['shenzhen']

為了避免,要進行循環(huán)嵌套

for names,places in favourite_places.items():  #對三個鍵值對先進行一個大循環(huán)
    print(f'{names.title()} favourite places are:') #在大循環(huán)里每一組鍵值對開頭先打印這句話
    for place in places:      #之后再對值進行一個小循環(huán),打印出值中的每個元素
        print(place.title())

輸出結(jié)果:

Lin favourite places are:
Beijing
Tianjin
Jing favourite places are:
Chengdu
Leshan
Huang favourite places are:
Shenzhen

3.字典中存儲字典

1.字典中不能全部由字典元素組成,會報錯。

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'

2.字典中的值可由字典組成

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-----------循環(huán)嵌套的方法輸出-------------------')
for username,userinfo in users.items():
    print('\n'+username+':')
    for name,age in userinfo.items():
        print(name,age)

輸出結(jié)果:

-----------直接訪問輸出-------------------
lin 21
xue 20

-----------循環(huán)嵌套的方法輸出-------------------

a:
name lin
age 21

b:
name xue
age 20

4.容易出的小錯誤:

1.訪問順序: 可以用dict_name[key] / dict_name.get(key)訪問字典的值,也可以用列表索引list_name[索引]訪問列表的值。但是要注意哪個在外,哪個在內(nèi),先訪問外層,再訪問內(nèi)層,直接訪問內(nèi)層的會出錯。

2.字典的值為列表,訪問的結(jié)果是輸出整個列表 需要嵌套循環(huán)遍歷里面的鍵值對。

3.字典中不能全部由字典元素組成

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

最新評論