Python3 字典中的items 函式

2021-08-07 15:35:41 字數 2013 閱讀 3885

python3:字典中的items()函式

作業系統:windows 10軟體版本:python-3.6.2-amd64編  者:wordzzzz

一、python2.x中items():

和之前一樣,本渣渣先貼出來python中help的幫助資訊:

>>> help(dict.items)

help on method_descriptor:

items(...)

d.items() -> list of d's (key, value) pairs, as 2-tuples

>>> help(dict.iteritems)

help on method_descriptor:

iteritems(...)

d.iteritems() -> an iterator over the (key, value) items of d

>>> help(dict.viewitems)

help on method_descriptor:

viewitems(...)

d.viewitems() -> a set-like object providing a view on d's items

在python2.x中,items( )用於 返回乙個字典的拷貝列表【returns a copy of the list of all items (key/value pairs) in d】,佔額外的記憶體。

iteritems() 用於返回本身字典列表操作後的迭代【returns an iterator on all items(key/value pairs) in d】,不占用額外的記憶體。

>>> d=

>>> type(d.items())

'list'>

>>> type(d.iteritems())

'dictionary-itemiterator'>

>>> type(d.viewitems())

'dict_items'>

二、python3.x中items():

>>> help(dict.items)

help on method_descriptor:

items(...)

d.items() -> a set-like object providing a view on d's items

python 3.x 裡面,iteritems() 和 viewitems() 這兩個方法都已經廢除了,而 items() 得到的結果是和 2.x 裡面 viewitems() 一致的。在3.x 裡 用 items()替換iteritems() ,可以用於 for 來迴圈遍歷。

>>> d=

>>> type(d.items())

簡單的例子:

d = 

sum = 0

for key, value in d.items():

sum = sum + value

print(key, ':' ,value)

print('平均分為:' ,sum /len(d))

輸出結果:

d:\users\wordzzzz\desktop>python3 test.py

adam : 95

lisa : 85

bart : 59

paul : 74

平均分為: 78.25

關於python3.x中items具體的應用,可以通過下面的傳送門到達機器學習實戰中找到:

完的汪(∪。∪)。。。zzz

python3字典遍歷 python3字典遍歷

python版本 python3.7 info infog.get name 得到字典info中name的值 info.keys 得到字典info中所有的鍵,結果是乙個物件 dict keys name age 需要注意在python2中該操作得到的是乙個列表 遍歷key for temp in i...

python3字典詳解 python3中字典詳解

字典 dict 1.建立字典的幾種方式 class dict kwarg class dict iterable,kwarg 使用上面的方法構建字典 方法1構建字典 a dict one 1,two 2,three 3 a輸出結果 方法2構建字典 a dict a輸出結果 方法3構建字典 d dic...

python3字典排序

說實話,對字典進行排序,這個說法本身就有問題,實際上,你無法對操縱字典說,字典,在你的底層實現裡,你就得按照我指定的順序來排列,如果這樣的話,字典就喪失了它的速度優勢,它也不是乙個字典了.好了,廢話不多說,我這裡稍微記錄一下我的做法吧.python2裡面原來是有dict.iteritems這樣乙個函...