4.1 一個簡單的字典(鍵值對)
# 外星人顏色(綠色)+分數(5)
alien_0 = {'color':'green','points':5}
print(alien_0['color']) #想要獲取值(green),指定字典名(alie_0)+鍵(color)
print(alien_0['points'])
#green
#5
4.2 新增鍵值對
字典是一種動態結構,可隨時在其中新增鍵值對,要新增鍵值對,可依次指定字典名、用方括號括起的鍵和相關聯的值。
alien_0 = {'color':'green','points':5}
print(alien_0)
# 新增外星人的x座標和y座標資訊
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#{'color':'green','points':5}
#{'color':'green','points':5,'x_position':0,'y_position':25}
① 修改字典中的值
alien_0 = {'color':'green','points':5,'speed':'medium'}
alien_0["color"] = 'yellow'
# 向右移動外星人
# 根據當前速度確定將外星人向右移動多遠
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
# 新位置為舊位置‘x_position’加上移動距離x_increment
aien_0['x_positin'] = alien_0['x_position'] + x_increment
print(f"New x_position:{alien_0['x_position']}")
#Original x-position:0
#New x-position:2
② 刪除鍵值對
del 字典名+要刪除的鍵:del alien_0['points']
③ 使用get()來訪問值
alien_0={'color':'green','speed':'slow'}
print(alien_0['points'])
# 直接輸出會報錯
point_value = alien_0.get('points','No points value assigned.') #不存在就返回第二個引數,沒有設定引數就返回none
print(point_value)
# No points value assigned
④ 遍歷字典
user_0={'username':'efermi', 'first':'enrico', 'last':'fermi'}
for key,value in user_0.items(): #不加items()就會報錯
print(f"\nKey:(key)")
print(f"Value:(value)")
⑤ 遍歷字典中的所有鍵或者值
keys()方法-返回一個字典所有的鍵
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_languages.keys(): #for name in sorted(favorite_languages.keys()):按順序排列
print(f"Hi{name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()},I see you love{language}!")
value()方法-返回字典中的所有值
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in favorite_languages.values(): #for name in set(favorite_languages.keys()):可去重
print(language.title())
4.3 巢狀
① 在列表中儲存字典
# 建立一個用於儲存外星人的空列表
aliens = []
# 建立30個綠色的外星人
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
# 顯示前5個外星人
for alien in aliens[:5]:
print(alien)
# 顯示
print("....")
# 顯示建立了多個外星人
print(f"Total number of aliens:{len(aiens)}")
② 在字典中儲存列表
# 儲存所點披薩的資訊
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
# 概述所點的披薩
print(f"You ordered a{pizza['crust']}-crust pizza with the following toppings:")
# for迴圈遍歷鍵‘toppings’
for topping in pizza['toppings']:
print("\t" + topping)
③ 在字典儲存字典
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
# 輸出
# Username:aeinstein
# Full name: Albert Einstein
# Location: Princeton
# Username:mcurie
# Full name: Marie Curie
# Location: Paris
for username,user_info in users.items():
print(f"\Username:{username}")
full_name = f"{user_infp['first']}(user_info['last']}"
location = user_info['location']
print(f"\tFull name:{full_name.title()}")
print(f"\tLocation:{location.title()}")