Python學習之路5-字典

《Python編程:從入門到實踐》筆記。
本章主要介紹字典的概念,基本操做以及一些進階操做。

1. 使用字典(Dict)

在Python中,字典是一系列鍵值對。每一個鍵都與一個值相關聯,用鍵來訪問值。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}

有時候,在空字典中添加鍵值對是爲了方便,而有時候則是必須這麼作,好比使用字典來存儲用戶提供的數據或在編寫能自動生成大量鍵值對的代碼時,此時一般要先定義一個空字典。ruby

# 代碼:
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不關心鍵值對的存儲順序,而只追蹤鍵與值之間的關聯關係。spa

2.2 遍歷字典中的全部鍵

字典的方法keys()將字典中的全部鍵以列表的形式返回,如下代碼遍歷字典中的全部鍵:.net

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

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

# 結果:
Jen
Sarah
Edward
Phil

也能夠用以下方法遍歷字典的全部鍵:code

# 代碼:
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 ~

相關文章
相關標籤/搜索