Dictionary sort the list sorted () methods and lambda operator .itemgetter

Examples

Let's declare a list of elements which dictionary

data = [
    {'age': 31, 'city': 'taipei', 'name': 'amy'},
    {'age': 71, 'city': 'tokyo', 'name': 'john'},
    {'age': 16, 'city': 'london', 'name': 'zoe'},
    {'age': 16, 'city': 'rio', 'name': 'cathy'},
    {'age': 48, 'city': 'frankfurt', 'name': 'david'}]

Sequence

We sort of age with sorted, key parameters passed in lambda, specify which elements are sorted according to

print(sorted(data, key=lambda x: x['age']))

Output:

[{'age': 16, 'city': 'london', 'name': 'zoe'},
 {'age': 16, 'city': 'rio', 'name': 'cathy'},
 {'age': 31, 'city': 'taipei', 'name': 'amy'},
 {'age': 48, 'city': 'frankfurt', 'name': 'david'},
 {'age': 71, 'city': 'tokyo', 'name': 'john'}]

Operator.itemgetter sorted using, instead of the function key sorted anonymous function, faster sorting, support multiple simultaneous sequencing keyword matching anonymous function, key and key functions the same applies min (), max (), and the like word

from operator import itemgetter
data = [
    {'age': 31, 'city': 'taipei', 'name': 'amy'},
    {'age': 71, 'city': 'tokyo', 'name': 'john'},
    {'age': 16, 'city': 'london', 'name': 'zoe'},
    {'age': 16, 'city': 'rio', 'name': 'cathy'},
    {'age': 48, 'city': 'frankfurt', 'name': 'david'}]
print(sorted(data, key=itemgetter('age')))

The results and the same as above

[{'age': 16, 'city': 'london', 'name': 'zoe'},
 {'age': 16, 'city': 'rio', 'name': 'cathy'},
 {'age': 31, 'city': 'taipei', 'name': 'amy'},
 {'age': 48, 'city': 'frankfurt', 'name': 'david'},
 {'age': 71, 'city': 'tokyo', 'name': 'john'}]
Published 146 original articles · won praise 66 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_38923792/article/details/103072659