Home  >  Article  >  Backend Development  >  The difference between iteriitems and items in sorted

The difference between iteriitems and items in sorted

Y2J
Y2JOriginal
2017-05-17 15:10:002072browse

If you want to get the descending ranking of the scores of each subject in dictionary a, the code is as follows.

a = {'math':98, 'english':100, 'PE':77}
b = sorted(a.iteritems(), key=operator.itemgetter(1), reverse=True)
c = sorted(a.items(), key=operator.itemgetter(1), reverse=True)

Both b and c can output the desired results, but what is the difference between these two methods in terms of operating mechanism and efficiency?

In fact, iteritems()Returns a generator that can traverse all key-value pairs

items()Returns a copy of the key-value pairs in the entire list. When the dict is relatively large, it will consume a lot of memory.

The items() in python3 is changed to the behavior of iteritems() and then Deletediteritems()

[Related recommendations]

1. Special recommendations: "php Programmer Toolbox" V0.1 version download

2. Python free video tutorial

3. The items() method for basic introduction to Python

4. Example of item() function traversing dictionary in Python

5. Detailed explanation of the usage of items() series functions in Python

6. Introducing three methods of accessing dictionaries

The above is the detailed content of The difference between iteriitems and items in sorted. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn