Detailed Explanation of items of Function Case in Python Dictionary
- 2021-11-29 08:01:01
- OfStack
Python3: items () function in dictionary
1. items () in Python2. x:
As with the previous one, the help information of help in python is posted first:
>>> 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
In Python2.x, items () is used to return a copy list of 1 dictionary, "Returns a copy of ES24list of all items (key/value pairs) in D", taking up extra memory.
iteritems () is used to return the iteration "Returns an iterator ES40all items (key/value pairs) in D" after its own dictionary list operation, and does not consume extra memory.
>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.viewitems())
<type 'dict_items'>
2. items () in Python3. x:
>>> help(dict.items)
Help on method_descriptor:
items(...)
D.items() -> a set-like object providing a view on D's items
In Python 3. x, both iteritems () and viewitems () have been abolished, while items () gives the same result as viewitems () 1 in 2. x. Replacing iteritems () with items () in 3. x can be used for for to loop through.
>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<class 'dict_items'>
Simple example:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
sum = 0
for key, value in d.items():
sum = sum + value
print(key, ':' ,value)
print(' Average score :' ,sum /len(d))
Output:
D:\Users\WordZzzz\Desktop > python3 test.py
Adam : 95
Lisa : 85
Bart : 59
Paul : 74
Average score: 78.25