搜尋
首頁後端開發Python教學三種方法使用For迴圈遍歷Python字典(實例詳解)

本篇文章為大家帶來了關於python的相關知識,其中主要介紹了關於怎麼使用for循環遍歷Python字典的三種方法,下面一起來看一下,希望對大家有幫助。

三種方法使用For迴圈遍歷Python字典(實例詳解)

推薦學習:python影片教學

在Python中,如何使用「for」迴圈遍歷字典?

今天我們將會示範三種方法,並學會遍歷巢狀字典。

在實戰前,我們需要先建立一個模擬資料的字典。

dict_1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First','Address':'Beijing'}

方法1:使用For 迴圈索引進行迭代

在Python 中遍歷字典的最簡單方法,就是將其直接放入for循環中。

Python 會自動將dict_1視為字典,並允許你迭代其key鍵。然後,我們就可以使用索引運算符,來取得每個value值。

for key in dict_1:
    print(key, ":", dict_1[key])

如果你想按照字母順序排列key鍵,可以使用sorted()方法,具體用法如下所示。

for key in sorted(dict_1):
    print(key, ":", dict_1[key])

方法2:使用.keys( ) 索引進行迭代

使用.keys()傳回包含字典鍵的Python 物件的方法,可以取得與方法1相同的結果。同樣,它也需要與索引運算子結合使用。

for key in dict_1.keys():
    print(key, '-->', dict_1[key])

方法3:使用.items( ) 進行迭代

其實,遍歷字典的最「pythonic」和優雅的方法,是使用.items()方法。

print(dict_1.items())

為了迭代transaction_data字典的鍵和值,您只需要「解包」嵌入在元組中的兩個項目,如下所示:

for k,v in dict_1.items():
    print(k,">>",v)

需要注意,kv只是「鍵」和「值」的標準別名,但你也可以選擇其他命名約定。

例如,我們可以更換成ab,也會有相同的輸出。

for a,b in dict_1.items():
    print(a,"-",b)

進階:遍歷巢狀字典

有時候,我們會遇到比較複雜的字典-嵌套字典。

那麼這種情況該怎麼辦呢?

dict_2 = {"num_1":{'Name': 'Zara', 'Age': 7, 'Class': 'First','Address':'Beijing'},
          "num_2":{'Name': 'BOb', 'Age': 32, 'Class': 'Six','Address':'Shanghai'},
          "num_3":{'Name': 'Tom', 'Age': 25, 'Class': 'Second','Address':'Wuhan'}}dict_2

為了解開屬於每個巢狀字典的鍵值對,我們可以這樣做:

for k, v in dict_2.items():
    if type(v) is dict:
        for nk, nv in v.items():
            print(nk, "→", nv)

透過if語句判斷value值是不是字典,如果是,則使用前面提到的方法3,使用.items( ) 進行迭代輸出。

運行結果如下圖所示。

如果只想解壓縮其中的部分字典,可以在if語句中增加條件。

for k, v in dict_2.items():
    if type(v) is dict and k == 'num_2':
        for sk, sv in v.items():
            print(sk, "-->", sv)

只輸出num_2的字典,運行結果如下圖所示。

以上,就是在Python中使用「for」迴圈遍歷字典的小技巧了。

推薦學習:python影片教學

#

以上是三種方法使用For迴圈遍歷Python字典(實例詳解)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:CSDN。如有侵權,請聯絡admin@php.cn刪除
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。