Python tutorial sorting different dictionaries through common keys

  • 2021-12-04 19:11:58
  • OfStack

This kind of structure is sorted by using itemgetter function in operator module.


rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]

Sorts according to the fields common to all dictionaries, which can be the dictionary's key name, numeric list element, or any value that can be passed to the object's __getitem__ () method.

If multiple tags are passed to itemgetter (), the callable object it produces will return tuples containing all elements, and sorted () will sort the output according to the sorting result of the tuples.


from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid')) 
print(rows_by_fname) 
# [{'fname': 'Big', 'uid': 1004, 'lname': 'Jones'},
# {'fname': 'Brian', 'uid': 1003, 'lname': 'Jones'},
# {'fname': 'David', 'uid': 1002, 'lname': 'Beazley'},
# {'fname': 'John', 'uid': 1001, 'lname': 'Cleese'}]
print(rows_by_uid) 
# [{'fname': 'John', 'uid': 1001, 'lname': 'Cleese'},
# {'fname': 'David', 'uid': 1002, 'lname': 'Beazley'},
# {'fname': 'Brian', 'uid': 1003, 'lname': 'Jones'},
# {'fname': 'Big', 'uid': 1004, 'lname': 'Jones'}]

When the itemgetter () function accepts multiple keys


rows_by_lfname = sorted(rows, key=itemgetter('lname', 'fname'))
print(rows_by_lfname)
# [{'fname': 'David', 'uid': 1002, 'lname': 'Beazley'},
# {'fname': 'John', 'uid': 1001, 'lname': 'Cleese'},
# {'fname': 'Big', 'uid': 1004, 'lname': 'Jones'},
# {'fname': 'Brian', 'uid': 1003, 'lname': 'Jones'}]

Similarly, itemgetter () applies to min () and max () functions


>>> min(rows, key=itemgetter('uid'))
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001}
>>> max(rows, key=itemgetter('uid'))
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}

The above is the Python tutorial through the public key to sort different dictionaries in detail, more about the Python public key to sort dictionaries for information please pay attention to other related articles on this site!


Related articles: