亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

Python學習之路5-字典

NicolasHe / 1095人閱讀

摘要:本章主要介紹字典的概念,基本操作以及一些進階操作。使用字典在中,字典是一系列鍵值對。中用花括號來表示字典。代碼定義空字典的語法結(jié)果如果要修改字典中的值,只需通過鍵名訪問就行。

《Python編程:從入門到實踐》筆記。
本章主要介紹字典的概念,基本操作以及一些進階操作。
1. 使用字典(Dict)

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

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

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

# 結(jié)果:
{"color": "green", "points": 5}
green
5

字典中可以包含任意數(shù)量的鍵值對,并且Python中字典是一個動態(tài)結(jié)構(gòu),可隨時向其中添加鍵值對。

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

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

# 結(jié)果:
{"color": "green", "points": 5}
{"color": "green", "points": 5, "x_position": 0, "y_position": 25}

有時候,在空字典中添加鍵值對是為了方便,而有時候則是必須這么做,比如使用字典來存儲用戶提供的數(shù)據(jù)或在編寫能自動生成大量鍵值對的代碼時,此時通常要先定義一個空字典。

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

# 結(jié)果:
{"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"] + ".")

# 結(jié)果:
The alien is green.
The alien is now yellow.

對于字典中不再需要的信息,可用del語句將相應(yīng)的鍵值對刪除:

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

del alien["color"]
print(alien)

# 結(jié)果:
{"color": "green", "points": 5}
{"points": 5}

前面的例子都是一個對象的多種信息構(gòu)成了一個字典(游戲中的外星人信息),字典也可以用來存儲眾多對象的統(tǒng)一信息:

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 + "
")

# 結(jié)果:
Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

這里有一點需要注意,遍歷字典時,鍵值對的返回順序不一定與存儲順序相同,Python不關(guān)心鍵值對的存儲順序,而只追蹤鍵與值之間的關(guān)聯(lián)關(guān)系。

2.2 遍歷字典中的所有鍵

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

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

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

# 結(jié)果:
Jen
Sarah
Edward
Phil

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

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

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

# 結(jié)果:
Jen
Sarah
Edward
Phil

但是帶有方法keys()的遍歷所表達的意思更明確。
還可以用keys()方法確定某關(guān)鍵字是否在字典中:

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

if "erin" not in favorite_languages.keys():
    print("Erin, please take our poll!")

# 結(jié)果:
Erin, please take our poll!

使用sorted()函數(shù)按順序遍歷字典中的所有鍵:

# 代碼:
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.")

# 結(jié)果:
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())

# 結(jié)果:
Python
C
Ruby
Python

從結(jié)果可以看出,上述代碼并沒有考慮去重的問題,如果想要去重,可以調(diào)用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())

# 結(jié)果:
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)

# 結(jié)果:
{"color": "green", "points": 5}
{"color": "yellow", "points": 10}
{"color": "red", "points": 15}
3.2 在字典中存儲列表

每當需要在字典中將一個鍵關(guān)聯(lián)到多個值時,都可以在字典中嵌套一個列表:

# 代碼:
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("	" + topping)

# 結(jié)果:
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("
Username: " + username)
    full_name = user_info["first"] + " " + user_info["last"]
    location = user_info["location"]

    print("	Full name: " + full_name.title())
    print("	Location: " + location.title())

# 結(jié)果:
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton

Username: mcurie
    Full name: Marie Curie
    Location: Paris
迎大家關(guān)注我的微信公眾號"代碼港" & 個人網(wǎng)站 www.vpointer.net ~

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/41797.html

相關(guān)文章

  • Python全棧之路系列之字典數(shù)據(jù)類型

    摘要:字典在基本的數(shù)據(jù)類型中使用頻率也是相當高的,而且它的訪問方式是通過鍵來獲取到對應(yīng)的值,當然存儲的方式也是鍵值對了,屬于可變類型。 字典(dict)在基本的數(shù)據(jù)類型中使用頻率也是相當高的,而且它的訪問方式是通過鍵來獲取到對應(yīng)的值,當然存儲的方式也是鍵值對了,屬于可變類型。 創(chuàng)建字典的兩種方式 第一種 >>> dic = {k1:123,k2:456} >>> dic {k1: 123, ...

    caoym 評論0 收藏0
  • Python學習之路6-用戶輸入和while循環(huán)

    摘要:本章主要介紹如何進行用戶輸入,循環(huán),以及與循環(huán)配合使用的語句。函數(shù)在中,使用函數(shù)獲取用戶輸入,這里請注意的返回值為字符串。值得提醒的是,編寫循環(huán)時應(yīng)避免死循環(huán),或者叫做無限循環(huán),比如循環(huán)忘記了變量自增。 《Python編程:從入門到實踐》筆記。本章主要介紹如何進行用戶輸入,while循環(huán),以及與循環(huán)配合使用的break, continue語句。 1. input() 函數(shù) 在Pytho...

    wfc_666 評論0 收藏0
  • Python學習之路15-下載數(shù)據(jù)

    摘要:本節(jié)中將繪制幅圖像收盤折線圖,收盤價對數(shù)變換,收盤價月日均值,收盤價周日均值,收盤價星期均值。對數(shù)變換是常用的處理方法之一。 《Python編程:從入門到實踐》筆記。本篇是Python數(shù)據(jù)處理的第二篇,本篇將使用網(wǎng)上下載的數(shù)據(jù),對這些數(shù)據(jù)進行可視化。 1. 前言 本篇將訪問并可視化以兩種常見格式存儲的數(shù)據(jù):CSV和JSON: 使用Python的csv模塊來處理以CSV(逗號分隔的值)...

    張春雷 評論0 收藏0
  • Python 進階之路 (二) Dict 進階寶典,初二快樂!

    摘要:新年快樂大家好,今天是大年初二,身在國外沒有過年的氛圍,只能踏實寫寫文章,對社區(qū)做點貢獻,在此祝大家新年快樂上一期為大家梳理了一些的進階用法,今天我們來看字典的相關(guān)技巧,我個人在編程中對字典的使用非常頻繁,其實對于不是非常大的數(shù)據(jù)存儲需求, 新年快樂 大家好,今天是大年初二,身在國外沒有過年的氛圍,只能踏實寫寫文章,對社區(qū)做點貢獻,在此祝大家新年快樂!上一期為大家梳理了一些List的進...

    ChristmasBoy 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<