亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python字典 dict幾種遍歷方式

 更新時間:2021年11月05日 15:53:34   作者:小小程序員ol  
這篇文章主要給大家分享的是Python字典 dict幾種遍歷方式,文章主要介紹使用 for key in dict遍歷字典、使用for key in dict.keys () 遍歷字典的鍵等內(nèi)容,需要的朋友可以參考一下,希望對你有所幫助

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',
    'author': '-----',
    'press': '人生苦短,我用python'
}

for key in book.keys():
    print(key)

# 輸出結(jié)果
title
author
press

3.使用 for values in dict.values () 遍歷字典的值

字典提供了 values () 方法返回字典中所有的值

'''
學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:725638078
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
# values
book = {
    'title': 'Python',
    'author': '-----',
    'press': '人生苦短,我用python'
}

for value in book.values():
    print(value)


# 輸出結(jié)果
Python
-----
人生苦短,我用python

4.使用 for item in dict.items () 遍歷字典的鍵值對

字典提供了 items () 方法返回字典中所有的鍵值對 item
鍵值對 item 是一個元組(第 0 項是鍵、第 1 項是值)

x = {'a': 'A', 'b': 'B'}
for item in x.items():
    key = item[0]
    value = item[1]
    print('%s   %s:%s' % (item, key, value))


# 輸出結(jié)果
('a', 'A')   a:A
('b', 'B')   b:B

5.使用 for key,value in dict.items () 遍歷字典的鍵值對

元組在 = 賦值運算符右邊的時候,可以省去括號

'''
學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:725638078
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
item = (1, 2)
a, b = item
print(a, b)


# 輸出結(jié)果
1 2


例:

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幾種遍歷方式的文章就介紹到這了,更多相關(guān)Python 字典 dict內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論