Python基礎資料類型之字典
字典(dict)能夠将相關資訊關聯起來;
字典可存儲的資訊量幾乎不受限制
一個簡單的字典
字典用放在花括号 { } 中的一系列鍵 — 值對表示;
鍵 — 值對是兩個相關聯的值;
指定鍵時,Python将傳回與之相關聯的值。鍵和值之間用冒号分隔,而鍵 — 值對之間用逗号分隔;
在字典中,想存儲多少個鍵 — 值對都可以
alien_0 = {'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
print(type(alien_0))
# green
# 5
# <class 'dict'>
使用字典
在Python中,字典是一系列鍵 — 值對;
每個鍵都與一個值相關聯,可以使用鍵來通路與之相關聯的值;
與鍵相關聯的值可以是數字、字元串、清單乃至字典。事實上,可将任何Python對象用作字典中的值;
通路字典中的值
要擷取與鍵相關聯的值,可依次指定字典名和放在方括号内的鍵
alien_0 = {'color':'green','points':5}
print(alien_0['color'])
# green
添加鍵值對
字典是一種動态結構,可随時在其中添加鍵 — 值對;
要添加鍵 — 值對,可依次指定字典名、用方括号括起的鍵和相關聯的值;
鍵 — 值對的排列順序與添加順序不同;
Python不關心鍵 — 值對的添加順序,而隻關心鍵和值之間的關聯關系
alien_0 = {'color':'green','points':5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
先建立一個空字典
使用字典來存儲使用者提供的資料或在編寫能自動生成大量鍵 — 值對的代碼時,通常都需要先定義一個空字典
alien = {}
alien['color'] = 'green'
alien['points'] = '5'
print(alien)
# {'color': 'green', 'points': '5'}
修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的鍵以及與該鍵相關聯的新值
alien_0 = {'color':'green','points':5}
alien_0['color'] = 'yellow'
print(alien_0)
# {'color':'yellow','points':5}
删除鍵—值對
del 語句:将相應的鍵—值對永久删除
alien_0 = {'color':'green','points':5}
del alien_0['points']
print(alien_0)
# {'color':'green'}
由類似對象組成的字典
确定需要使用多行來定義字典時,在輸入左花括号後按Enter鍵
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print(favorite_languages)
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
# {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
# Sarah's favorite language is C.
周遊字典
可以使用循環來周遊字典,需要指定周遊方法;
下面将介紹周遊字典的方法
周遊所有的鍵—值對
使用 for 循環來周遊字典,在對字典使用 items() 方法;
聲明兩個變量,用于存儲鍵 — 值對中的鍵和值。對于這兩個變量,可使用任何名稱;
方法 items() :傳回一個鍵 — 值對清單
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
# Jen's favorite language is Python.
# Sarah's favorite language is C.
# Edward's favorite language is Ruby.
# Phil's favorite language is Python.
即便周遊字典時,鍵 — 值對的傳回順序也可能與存儲順序不同;
Python不關心鍵 — 值對的存儲順序,而隻跟蹤鍵和值之間的關聯關系
周遊字典中的所有鍵
方法 keys() : 傳回字典中的所有鍵
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
# Jen
# Sarah
# Edward
# Phil
周遊字典時,會預設周遊所有的鍵,是以即使不使用方法 keys() ,輸出也将不變;
使用方法 keys() 可以讓代碼更容易了解,也可以省略它 for name in favorite_languages:
方法 keys() 并非隻能用于周遊;實際上,它傳回一個清單,其中包含字典中的所有鍵
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
# Erin, please take our poll!
按順序周遊字典中的所有鍵
要以特定的順序傳回元素,一種辦法是在 for 循環中對傳回的鍵進行排序,
為此,可使用函數 sorted() 來獲得按特定順序排列的鍵清單的副本
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# Erin, please take our poll!
# Edward, thank you for taking the poll.
# Jen, thank you for taking the poll.
# Phil, thank you for taking the poll.
周遊字典中所有的值
方法 values() : 傳回一個值清單,而不包含任何鍵
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mengtioned:")
for language in sorted(favorite_languages.values()):
print(language.title())
# The following languages have been mengtioned:
# C
# Python
# Python
# Ruby
剔除重複項
方法 set() : 剔除重複項
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for language in set(favorite_languages.values()):
print(language.title())
# C
# Python
# Ruby
嵌套
将一系列字典存儲在清單中,或将清單作為值存儲在字典中,稱為嵌套;
可以在清單中嵌套字典、在字典中嵌套清單、在字典中嵌套字典
将字典存儲在清單中
# 建立一個包含三個外星人的清單:
alien_0 = {'color':'green','points':'5'}
alien_1 = {'color':'yellow','points':'10'}
alien_2 = {'color':'red','points':'15'}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
# {'color': 'green', 'points': '5'}
# {'color': 'yellow', 'points': '10'}
# {'color': 'red', 'points': '15'}
将清單存儲在字典中
每當需要在字典中将一個鍵關聯到多個值時,都可以在字典中嵌套一個清單.
pizza = {
'crust' : 'thick',
'toppings' : ['mushrooms','extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the follwing toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
# You ordered a thick-crust pizza with the follwing toppings:
# mushrooms
# extra cheese
将字典存儲在字典中
可在字典中嵌套字典,但這樣做時,代碼可能很快複雜起來
例如,如果有多個網站使用者,每個都有獨特的使用者名,可在字典中将使用者名作為鍵,然後将每位使用者的資訊存儲在一個字典中,并将該字典作為與使用者名相關聯的值
users = {
'aeinstein' : {
'first' : 'albert',
'last' : 'einstein',
'location' : 'princeton',
},
'mcurie' : {
'first' : 'marie' ,
'last' : 'curie' ,
'location' : 'paris' ,
}
}
for username,user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation :" + location.title())
# Username: aeinstein
# Full name: Albert Einstein
# Location :Princeton
# Username: mcurie
# Full name: Marie Curie
# Location :Paris