摘要:本章主要介紹字典的概念,基本操作以及一些進(jìn)階操作。使用字典在中,字典是一系列鍵值對(duì)。中用花括號(hào)來表示字典。代碼定義空字典的語法結(jié)果如果要修改字典中的值,只需通過鍵名訪問就行。
《Python編程:從入門到實(shí)踐》筆記。1. 使用字典(Dict)
本章主要介紹字典的概念,基本操作以及一些進(jìn)階操作。
在Python中,字典是一系列鍵值對(duì)。每個(gè)鍵都與一個(gè)值相關(guān)聯(lián),用鍵來訪問值。Python中用花括號(hào){}來表示字典。
# 代碼: alien = {"color": "green", "points": 5} print(alien) # 輸出字典 print(alien["color"]) # 輸出鍵所對(duì)應(yīng)的值 print(alien["points"]) # 結(jié)果: {"color": "green", "points": 5} green 5
字典中可以包含任意數(shù)量的鍵值對(duì),并且Python中字典是一個(gè)動(dòng)態(tài)結(jié)構(gòu),可隨時(shí)向其中添加鍵值對(duì)。
# 代碼: 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í)候,在空字典中添加鍵值對(duì)是為了方便,而有時(shí)候則是必須這么做,比如使用字典來存儲(chǔ)用戶提供的數(shù)據(jù)或在編寫能自動(dòng)生成大量鍵值對(duì)的代碼時(shí),此時(shí)通常要先定義一個(gè)空字典。
# 代碼: 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.
對(duì)于字典中不再需要的信息,可用del語句將相應(yīng)的鍵值對(duì)刪除:
# 代碼: alien = {"color": "green", "points": 5} print(alien) del alien["color"] print(alien) # 結(jié)果: {"color": "green", "points": 5} {"points": 5}
前面的例子都是一個(gè)對(duì)象的多種信息構(gòu)成了一個(gè)字典(游戲中的外星人信息),字典也可以用來存儲(chǔ)眾多對(duì)象的統(tǒng)一信息:
favorite_languages = { "jen": "python", "sarah": "c", "edward": "ruby", "phil": "python", # 建議在最后一項(xiàng)后面也加個(gè)逗號(hào),便于之后添加元素 }2. 遍歷字典 2.1 遍歷所有的鍵值對(duì)
# 代碼: 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
這里有一點(diǎn)需要注意,遍歷字典時(shí),鍵值對(duì)的返回順序不一定與存儲(chǔ)順序相同,Python不關(guān)心鍵值對(duì)的存儲(chǔ)順序,而只追蹤鍵與值之間的關(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()的遍歷所表達(dá)的意思更明確。
還可以用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 Ruby3. 嵌套 3.1 字典列表
以前面外星人為例,三個(gè)外星人組成一個(gè)列表:
# 代碼: 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 在字典中存儲(chǔ)列表
每當(dāng)需要在字典中將一個(gè)鍵關(guān)聯(lián)到多個(gè)值時(shí),都可以在字典中嵌套一個(gè)列表:
# 代碼: 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 cheese3.3 在字典中存儲(chǔ)字典
涉及到這種情況時(shí),代碼都不會(huì)簡單:
# 代碼: 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)注我的微信公眾號(hào)"代碼港" & 個(gè)人網(wǎng)站 www.vpointer.net ~
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/41797.html
摘要:字典在基本的數(shù)據(jù)類型中使用頻率也是相當(dāng)高的,而且它的訪問方式是通過鍵來獲取到對(duì)應(yīng)的值,當(dāng)然存儲(chǔ)的方式也是鍵值對(duì)了,屬于可變類型。 字典(dict)在基本的數(shù)據(jù)類型中使用頻率也是相當(dāng)高的,而且它的訪問方式是通過鍵來獲取到對(duì)應(yīng)的值,當(dāng)然存儲(chǔ)的方式也是鍵值對(duì)了,屬于可變類型。 創(chuàng)建字典的兩種方式 第一種 >>> dic = {k1:123,k2:456} >>> dic {k1: 123, ...
摘要:本章主要介紹如何進(jìn)行用戶輸入,循環(huán),以及與循環(huán)配合使用的語句。函數(shù)在中,使用函數(shù)獲取用戶輸入,這里請(qǐng)注意的返回值為字符串。值得提醒的是,編寫循環(huán)時(shí)應(yīng)避免死循環(huán),或者叫做無限循環(huán),比如循環(huán)忘記了變量自增。 《Python編程:從入門到實(shí)踐》筆記。本章主要介紹如何進(jìn)行用戶輸入,while循環(huán),以及與循環(huán)配合使用的break, continue語句。 1. input() 函數(shù) 在Pytho...
摘要:本節(jié)中將繪制幅圖像收盤折線圖,收盤價(jià)對(duì)數(shù)變換,收盤價(jià)月日均值,收盤價(jià)周日均值,收盤價(jià)星期均值。對(duì)數(shù)變換是常用的處理方法之一。 《Python編程:從入門到實(shí)踐》筆記。本篇是Python數(shù)據(jù)處理的第二篇,本篇將使用網(wǎng)上下載的數(shù)據(jù),對(duì)這些數(shù)據(jù)進(jìn)行可視化。 1. 前言 本篇將訪問并可視化以兩種常見格式存儲(chǔ)的數(shù)據(jù):CSV和JSON: 使用Python的csv模塊來處理以CSV(逗號(hào)分隔的值)...
摘要:新年快樂大家好,今天是大年初二,身在國外沒有過年的氛圍,只能踏實(shí)寫寫文章,對(duì)社區(qū)做點(diǎn)貢獻(xiàn),在此祝大家新年快樂上一期為大家梳理了一些的進(jìn)階用法,今天我們來看字典的相關(guān)技巧,我個(gè)人在編程中對(duì)字典的使用非常頻繁,其實(shí)對(duì)于不是非常大的數(shù)據(jù)存儲(chǔ)需求, 新年快樂 大家好,今天是大年初二,身在國外沒有過年的氛圍,只能踏實(shí)寫寫文章,對(duì)社區(qū)做點(diǎn)貢獻(xiàn),在此祝大家新年快樂!上一期為大家梳理了一些List的進(jìn)...
閱讀 4956·2023-04-25 18:47
閱讀 2688·2021-11-19 11:33
閱讀 3456·2021-11-11 16:54
閱讀 3112·2021-10-26 09:50
閱讀 2559·2021-10-14 09:43
閱讀 682·2021-09-03 10:47
閱讀 687·2019-08-30 15:54
閱讀 1513·2019-08-30 15:44