python中對字典(dict)的迭代__python

來源:互聯網
上載者:User
#!/usr/bin/python#coding: utf-8d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }# 迭代dict的鍵for x in d.keys():    print x# 也可以採用這種方式迭代for x in d.iterkeys():    print x# 迭代dict的值for x in d.values():    print xfor x in d.itervalues():    print x# 迭代索引值對for k, v in d.items():    print k, ":", vfor k, v in d.iteritems():    print k, ":", v'''上述代碼中,對索引值或者是索引值對迭代的方法都有兩種,以values和itervalues為例,說明這兩種方式的區別1. values() 方法實際上把一個 dict 轉換成了包含 value 的list。2. 但是 itervalues() 方法不會轉換,它會在迭代過程中依次從 dict 中取出 value,所以 itervalues() 方法比 values() 方法節省了產生 list 所需的記憶體。3. 列印 itervalues() 發現它返回一個 <dictionary-valueiterator> 對象,這說明在Python中,for 迴圈可作用的迭代對象遠不止 list,tuple,str,unicode,dict等,任何可迭代對象都可以作用於for迴圈,而內部如何迭代我們通常並不用關心print d.itervalues()# <dictionary-valueiterator object at 0x0137F8A0>關於迭代如果一個對象說自己可迭代,那我們就直接用 for 迴圈去迭代它,可見,迭代是一種抽象的資料操作,它不對迭代對象內部的資料有任何要求。'''

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.