Python學習之路5-字典

VPointer發表於2018-05-29

《Python程式設計:從入門到實踐》筆記。

本章主要介紹字典的概念,基本操作以及一些進階操作。

1. 使用字典(Dict)

在Python中,字典是一系列鍵值對。每個鍵都與一個值相關聯,用鍵來訪問值。Python中用花括號{}來表示字典。

# 程式碼:
alien = {"color": "green", "points": 5}

print(alien)  # 輸出字典
print(alien["color"])   # 輸出鍵所對應的值
print(alien["points"])

# 結果:
{'color': 'green', 'points': 5}
green
5
複製程式碼

字典中可以包含任意數量的鍵值對,並且Python中字典是一個動態結構,可隨時向其中新增鍵值對。

# 程式碼:
alien = {"color": "green", "points": 5}
print(alien)

alien["x_position"] = 0
alien["y_position"] = 25
print(alien)

# 結果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
複製程式碼

有時候,在空字典中新增鍵值對是為了方便,而有時候則是必須這麼做,比如使用字典來儲存使用者提供的資料或在編寫能自動生成大量鍵值對的程式碼時,此時通常要先定義一個空字典。

# 程式碼:
alien = {}    # 定義空字典的語法
alien["x_position"] = 0
alien["y_position"] = 25
print(alien)

# 結果:
{'x_position': 0, 'y_position': 25}
複製程式碼

如果要修改字典中的值,只需通過鍵名訪問就行。

# 程式碼:
alien = {"color" : "green"}
print("The alien is " + alien["color"] + ".")

alien["color"] = "yellow"
print("The alien is now " + alien["color"] + ".")

# 結果:
The alien is green.
The alien is now yellow.
複製程式碼

對於字典中不再需要的資訊,可用del語句將相應的鍵值對刪除:

# 程式碼:
alien = {"color": "green", "points": 5}
print(alien)

del alien["color"]
print(alien)

# 結果:
{'color': 'green', 'points': 5}
{'points': 5}
複製程式碼

前面的例子都是一個物件的多種資訊構成了一個字典(遊戲中的外星人資訊),字典也可以用來儲存眾多物件的統一資訊:

favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",   # 建議在最後一項後面也加個逗號,便於之後新增元素
}
複製程式碼

2. 遍歷字典

2.1 遍歷所有的鍵值對

# 程式碼:
user_0 = {
    "username": "efermi",
    "first": "enrico",
    "last": "fermi",
}

for key, value in user_0.items():
    print("Key: " + key)
    print("Value: " + value + "\n")

# 結果:
Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi
複製程式碼

這裡有一點需要注意,遍歷字典時,鍵值對的返回順序不一定與儲存順序相同,Python不關心鍵值對的儲存順序,而只追蹤鍵與值之間的關聯關係。

2.2 遍歷字典中的所有鍵

字典的方法keys()將字典中的所有鍵以列表的形式返回,以下程式碼遍歷字典中的所有鍵:

# 程式碼:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

for name in favorite_languages.keys():
    print(name.title())

# 結果:
Jen
Sarah
Edward
Phil
複製程式碼

也可以用如下方法遍歷字典的所有鍵:

# 程式碼:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

for name in favorite_languages:
    print(name.title())

# 結果:
Jen
Sarah
Edward
Phil
複製程式碼

但是帶有方法keys()的遍歷所表達的意思更明確。 還可以用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!
複製程式碼

使用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.")

# 結果:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
複製程式碼

2.3 遍歷字典中的所有值

類似於遍歷所有鍵用keys()方法,遍歷所有值則使用values()方法

# 程式碼:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

# 結果:
Python
C
Ruby
Python
複製程式碼

從結果可以看出,上述程式碼並沒有考慮去重的問題,如果想要去重,可以呼叫set()

# 程式碼:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

# 結果:
Python
C
Ruby
複製程式碼

3. 巢狀

3.1 字典列表

以前面外星人為例,三個外星人組成一個列表:

# 程式碼:
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}
複製程式碼

3.2 在字典中儲存列表

每當需要在字典中將一個鍵關聯到多個值時,都可以在字典中巢狀一個列表:

# 程式碼:
pizza = {
    "crust": "thick",
    "toppings": ["mushrooms", "extra cheese"],
}

print("You ordered a " + pizza["crust"] + "-crust pizza" +
      "with the following toppings:")

for topping in pizza["toppings"]:
    print("\t" + topping)

# 結果:
You ordered a thick-crust pizzawith the following toppings:
	mushrooms
	extra cheese
複製程式碼

3.3 在字典中儲存字典

涉及到這種情況時,程式碼都不會簡單:

# 程式碼:
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
複製程式碼

迎大家關注我的微信公眾號"程式碼港" & 個人網站 www.vpointer.net ~

Python學習之路5-字典

相關文章