在 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 次浏览

开启您的 职业

通过完成课程获取证书

开始
广告
© . All rights reserved.