Get the App
SLTechnology News&Howtos  ›  Development  › 

How Python sorts different dictionaries through public keys

Shulou Source: shulou.com Published: 2022-06-03 09:06:11 10月04日 Update

This article mainly shows you "how Python sorts different dictionaries through public keys". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how Python sorts different dictionaries through public keys".

This kind of structure is sorted by the itemgetter function in the 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}]

Sort by the fields common to all dictionaries, which can be the key name of the dictionary, a list element represented by a number, or any value that can be passed to the _ _ getitem__ () method of the object.

If multiple tags are passed to itemgetter (), the callable object it produces will return a tuple containing all elements, and then sorted () will sort the output based on the sort result of the tuple.

From operator import itemgetterrows_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'}]

Itemgetter () also 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} is all the contents of the article "how Python sorts different dictionaries through public keys". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Sort dictionary different content function article element multiple field object result learning help name number method easy to understand more organization tag Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft Apple Shulou Technology MySQL