Python3實現的字典遍曆操作詳解

來源:互聯網
上載者:User
這篇文章主要介紹了Python3實現的字典遍曆操作,結合執行個體形式分析了Python3針對字典鍵、索引值及索引值對遍曆的相關操作技巧,需要的朋友可以參考下

本文執行個體講述了Python3字典遍曆操作。分享給大家供大家參考,具體如下:

字典是針對非序列集合而提供的一種資料類型。

通過任意鍵尋找集合中值資訊的過程叫映射,python通過字典實現映射。

為字典賦值:

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> print(d){1: 123, 'list': [1, 2, 3], '111': 'python3', 'tuple': (4, 5, 6)}

以上語句說明,字典中各項的順序與賦值時的順序可能不一致,即字典是無序的。

字典的遍曆有一下幾種:

1. 遍曆字典的鍵key

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for key in d:    print(str(key)+':'+str(d[key]))list:[1, 2, 3]1:123111:python3tuple:(4, 5, 6)

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for key in d.keys():    print(key)1list111tuple

2. 遍曆字典的值value

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for value in d.values():    print (value)[1, 2, 3]123python3(4, 5, 6)

3. 遍曆字典的項

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for item in d.items():    print(item)('list', [1, 2, 3])(1, 123)('111', 'python3')('tuple', (4, 5, 6))

4. 遍曆字典的key-value

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for key,value in d.items():    print(key,value)list [1, 2, 3]1 123111 python3tuple (4, 5, 6)

>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}>>> for (key,value) in d.items():    print(key,value)list [1, 2, 3]1 123111 python3tuple (4, 5, 6)

上述樣本運行效果如所示:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.