在 Python 中迭代字典


在本文中,我們將瞭解 Python 3.x 中字典的迭代/遍歷。或者更早版本。

字典是無序的鍵值對序列。索引可以是任何不可變型別並且稱為鍵。這也用大括號指定。

方法 1 − 直接使用可迭代物件

例項

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp:
   print(value, end='')

輸出

trason

方法 2 − 根據字典值使用可迭代物件

例項

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp.values():
   print(value, end='')

輸出

oilpit

方法 3 − 使用鍵作為索引

例項

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp:
   print(dict_inp[value], end='')

輸出

oilpit

方法 4 − 使用字典的鍵和值

例項

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value,char in dict_inp.items():
   print(value,":",char, end=" ")

輸出

t : o r : i a : l s : p o : i n : t

結論

在本文中,我們學習了 Python 中字典的迭代/遍歷。

更新日期: 2020-07-01

249 次瀏覽

開啟您的 職業

透過完成課程獲取證書

開始
廣告