在 Python 中迭代字典
pythonserver side programmingprogramming更新于 2025/6/1 23:08:17
在本文中,我们将学习 Python 3.x 或更早版本中字典的迭代/遍历。
字典是键值对的无序序列。索引可以是任何不可变类型,称为键。这也在花括号内指定。
方法 1 −直接使用可迭代对象
示例
dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# 迭代字符串
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'}
# 迭代字符串
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'}
# 遍历字符串
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'}
# 遍历字符串
for value,char in dict_inp.items():
print(value,":",char, end=" ")
输出
t : o r : i a : l s : p o : i n : t
结论
在本文中,我们了解了 Python 中字典的迭代/遍历。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

