1.使用 for key in dict 遍歷字典
可以使用 for key in dict 遍歷字典中所有的鍵
x = {'a': 'A', 'b': 'B'}
for key in x:
print(key)
# 輸出結(jié)果
a
b
2.使用 for key in dict.keys () 遍歷字典的鍵
字典提供了 keys () 方法返回字典中所有的鍵
# keys
book = {
'title': 'Python 入門基礎(chǔ)',
'author': '張三',
'press': '機械工業(yè)出版社'
}
for key in book.keys():
print(key)
# 輸出結(jié)果
title
author
press
3.使用 for values in dict.values () 遍歷字典的值
字典提供了 values () 方法返回字典中所有的值
# values
book = {
'title': 'Python 入門基礎(chǔ)',
'author': '張三',
'press': '機械工業(yè)出版社'
}
for value in book.values():
print(value)
# 輸出結(jié)果
Python 入門基礎(chǔ)
張三
機械工業(yè)出版社
4.使用 for item in dict.items () 遍歷字典的鍵值對
字典提供了 items () 方法返回字典中所有的鍵值對 item
鍵值對 item 是一個元組(第 0 項是鍵、第 1 項是值)文章來源:http://www.zghlxwxcb.cn/news/detail-711486.html
x = {'a': 'A', 'b': 'B'}
for item in x.items():
key = item[0]
value = item[1]
print('%s %s:%s' % (item, key, value))
#Python小白學習交流群:153708845
# 輸出結(jié)果
('a', 'A') a:A
('b', 'B') b:B
5.使用 for key,value in dict.items () 遍歷字典的鍵值對
item = (1, 2)
a, b = item
print(a, b)
# 輸出結(jié)果
1 2
例子文章來源地址http://www.zghlxwxcb.cn/news/detail-711486.html
x = {'a': 'A', 'b': 'B'}
for key, value in x.items():
print('%s:%s' % (key, value))
# 輸出結(jié)果
a:A
b:B
到了這里,關(guān)于Python中dict字典的多種遍歷方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!