A program that sorts lists (list), dictionaries (dict) in Python

Source: Internet
Author: User
Tags sorts

The sort in Python3 has been made very clear in sorting how. For a practical example, the following list is sorted based on the creation time:

pages = [
{' title ': ' Ten-year Learning program ', ' Time ': ' 2012-02-14 ', ' name ': ' 21-days '},
{' title ': ' ANE Toolkit ', ' time ': ' 2012-06-07 ', ' name ': ' Anetoolkit '},
{' title ': ' Cocos2d-x-filters ', ' time ': ' 2015-05-06 ', ' name ': ' Cocos2d-x-filters '},
{' title ': ' My Firefox plugin ', ' time ': ' 2006-05-23 ', ' name ': ' Firefox-addons '},
{' title ': ' Flash&flex Daquan ', ' time ': ' 2005-11-02 ', ' name ': ' Flashassistant '},
{' title ': ' The wisdom of questioning ', ' time ': ' 2005-10-08 ', ' name ': ' Howtoask '},
{' title ': ' Linux software ', ' time ': ' 2009-04-30 ', ' name ': ' Linux-software '},
{' title ': ' Platform ANEs ', ' time ': ' 2013-08-22 ', ' name ': ' Platform-anes '},
{' title ': ' Read ', ' time ': ' 2015-03-03 ', ' name ': ' Read '},
{' title ': ' Sprite Sheet Editor ', ' time ': ' 2011-08-18 ', ' name ': ' Sprite_sheet_editor '},
{' title ': ' Spritesheetpacker ', ' time ': ' 2011-04-19 ', ' name ': ' Spritesheetpacker '},
{' title ': ' WordPress encyclopedia ', ' time ': ' 2006-03-07 ', ' name ': ' Wordpressfavorite '},
{' title ': ' Wpcmd ', ' time ': ' 2015-06-12 ', ' name ': ' Wpcmd '}
]
First, the sort requires an object that can be compared, and I use the key named object in index:

From datetime import Date

For item in pages:
t = item[' time '].split ('-')
item[' index ' = date (int (t[0]), int (t[1]), int (t[2])
The instance of date is comparable (it implements the __lt__ set of methods), date (2012,2,14) < data (2005, one, 2) = = False.

Then, call the Sort method on pages:

Pages.sort (key=lambda item:item[' index ')
Here, I need to pass a function for key, which returns the value that needs to be compared.

Of course, you can also use the Itemgetter method provided by operator to get the value you want to compare.

From operator Import Itemgetter
Names.sort (Key=itemgetter (' index '))
In addition to Itemgetter, the operator module provides attrgetter and Methodcaller.

Zhang He to the above mentioned sorting mini-how to do some necessary Chinese commentary, this article and sorting how to basically the same.

Sort a dictionary list by a keyword

By using the Itemgetter function of the operator module, it is very easy to sort such data structures. Suppose you retrieve a list of site membership information from the database and return it with the following data structure:

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}
]
Sorting the input result rows according to any of the dictionary fields is easy to implement, and the code example:

From operator Import Itemgetter
Rows_by_fname = sorted (rows, Key=itemgetter (' fname '))
Rows_by_uid = sorted (rows, key=itemgetter (' uid '))
Print (Rows_by_fname)
Print (ROWS_BY_UID)
The output of the code is as follows:

[{' fname ': ' Big ', ' uid ': 1004, ' lname ': ' Jones '},
{' fname ': ' Brian ', ' uid ': 1003, ' lname ': ' Jones '},
{' fname ': ' David ', ' uid ': 1002, ' lname ': ' Beazley '},
{' fname ': ' John ', ' uid ': 1001, ' lname ': ' Cleese '}]
[{' fname ': ' John ', ' uid ': 1001, ' lname ': ' Cleese '},
{' fname ': ' David ', ' uid ': 1002, ' lname ': ' Beazley '},
{' fname ': ' Brian ', ' uid ': 1003, ' lname ': ' Jones '},
{' fname ': ' Big ', ' uid ': 1004, ' lname ': ' Jones '}]
The Itemgetter () function also supports multiple keys, such as the following code

Rows_by_lfname = sorted (rows, Key=itemgetter (' lname ', ' fname '))
Print (Rows_by_lfname)
will produce the following output:

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

Discuss
In the example above, rows is passed to the sorted () built-in function that accepts a keyword argument. This parameter is the callable type, and accepts a single element from rows and returns the value to be used for sorting. The Itemgetter () function is responsible for creating the callable object.

The Operator.itemgetter () function has an index parameter that is used by records in rows to look up values. Can be a dictionary key name, an integer value, or any value that can pass in an object's __getitem__ () method. If you pass in multiple index parameters to Itemgetter (), the resulting callable object returns a tuple containing all the element values, and the sorted () function is sorted according to the order of the elements in the tuple. This is useful when you want to sort on several fields at the same time (for example, by first name and first name).

Itemgetter () can sometimes be replaced with lambda expressions, such as:

Rows_by_fname = sorted (rows, Key=lambda r:r[' fname ')
Rows_by_lfname = sorted (rows, Key=lambda r: (r[' lname '],r[' fname '))
That's a good plan. However, using the Itemgetter () method will run slightly faster. Therefore, if you have high performance requirements, use the Itemgetter () method.

Finally, don't forget that the techniques shown in this section also apply to functions such as min () and Max (). Like what:

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


Sorting objects that do not support native comparisons

The built-in sorted () function has a keyword parameter key that can pass in a callable object to it, which returns a value for each incoming object that is sorted used to sort the objects. For example, if you have a sequence of user instances in your application and you want to sort by their user_id property, you can provide a callable object that takes the user instance as input and outputs the corresponding user_id value. Like what:

Class User:
def __init__ (self, user_id):
self.user_id = user_id

def __repr__ (self):
Return ' User ({}) '. Format (self.user_id)


Def sort_notcompare ():
Users = [User (+), User (3), User (99)]
Print (users)
Print (sorted (users, Key=lambda u:u.user_id))
Another way is to use Operator.attrgetter () instead of a lambda function:

>>> from operator Import Attrgetter
>>> sorted (Users, Key=attrgetter (' user_id '))
[User (3), user (+), User (99)]
>>>

Discuss
Choosing to use a lambda function or attrgetter () may depend on your preferences. However, the Attrgetter () function typically runs faster and allows multiple fields to be compared at the same time. This is similar to the Operator.itemgetter () function for dictionary types (refer to section 1.13). For example, if the user instance also has a first_name and last_name property, you can sort the following:

By_name = sorted (Users, Key=attrgetter (' last_name ', ' first_name '))
It is also important to note that the techniques used in this section also apply to functions such as min () and Max (). Like what:

>>> min (Users, Key=attrgetter (' user_id ')
User (3)
>>> Max (Users, Key=attrgetter (' user_id ')
User (99)
>>>

A program that sorts lists (list), dictionaries (dict) in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.