為什麼需要嵌套?
有時候,需要将一系列字典存儲在清單中,或将清單作為值存儲在字典中,這稱為嵌套 。你可以在清單中嵌套字典、在字典中嵌套清單甚至在字典中嵌套字典。
字典清單
例如:字典alien_0包含一個外星人的資訊,但無法存儲第二個外星人的資訊。怎麼辦呢?
我們可以建立三個外星人字典,那麼問題來了,我們需要的是大量的外星人,有沒有更簡單的方式呢?
?
1
2
3
alien_0= {'color':'blue','points':'5'}
alien_1= {'color':'blue','points':'5'}
alien_2= {'color':'blue','points':'5'}
?
1
2
3
4
5
6
7
aliens= []
for numberin range(5):
new_alient= {'color':'blue','points':'5','speed':'slow'}
aliens.append(new_alient)
for iin aliens:
print(i)
print(str(len(aliens)))
輸出
{'color': 'blue', 'points': '5', 'speed': 'slow'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
5
這些外星人都有相同的特征。在python看來,每個外星人都是獨立的,但是這樣并不符合業務需求。
例如:将前三個外星人修改成黃色、速度中等且值為10個點
?
1
2
3
4
5
6
7
8
9
10
11
aliens= []
for numberin range(5):
new_alient= {'color':'blue','points':'5','speed':'slow'}
aliens.append(new_alient)
for alienin aliens[:3]:
if alien['color']== 'blue':
alien['color']= 'yellow'
alien['speen']= 'medium'
alien['points']= 10
for alienin aliens:
print(alien)
輸出
{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'slow', 'speen': 'medium'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
這裡還可以使用if-elif-else語句,更加詳細的表述每個外星人的屬性。
在字典中存儲清單
例如:買煎餅果子的時候,使用清單的話可以描述煎餅果子可以加什麼配料。如果使用字典,不僅能描述配料,還能描述煎餅果子的産地等資訊
?
1
2
3
4
jbgz= {'origin':'天津','toppings':['雞蛋','香腸']}
print('煎餅果子産地是:' + jbgz['origin']+ '。你可以選擇添加:')
for toppingin jbgz['toppings']:
print(topping)
輸出
煎餅果子産地是:天津。你可以選擇添加:
雞蛋
香腸
例如:調查程式員們喜歡都喜歡什麼程式設計語言
?
1
2
3
4
5
6
7
8
9
languages= {
'jens':['python','java'],
'sarah':['c','ruby'],
'hack':['go']
}
for name,languagein languages.items():
print(name.title()+ "'s favorite languages are:")
for iin language:
print('\t' + i.title())
輸出
Jens's favorite languages are:
Python
Java
Sarah's favorite languages are:
C
Ruby
Hack's favorite languages are:
Go
在字典中存儲字典
例如:網站記憶體儲每個使用者的姓、名、住址,通路這些資訊
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
users= {
'嶽雲鵬':{
'姓':'嶽',
'名':'龍剛',
'住址':'北京'
},
'孟鶴堂':{
'姓':'孟',
'名':'祥輝',
'住址':'北京'
}
}
for username,user_infoin users.items():
print('\n藝名:'+ username)
full_name= user_info['姓']+ '' + user_info['名']
location= user_info['住址']
print('\t姓名:' + full_name)
print('\t住址:' + location)
輸出
藝名:嶽雲鵬
姓名:嶽龍剛
住址:北京
藝名:孟鶴堂
姓名:孟祥輝
住址:北京
以上就是淺析python 字典嵌套的詳細内容,更多關于python 字典嵌套的資料請關注伺服器之家其它相關文章!
原文連結:https://www.cnblogs.com/Bcxc/p/13740505.html