Python3 Dict list In order to sort examples

Source: Internet
Author: User

The sort in the Python3 has been made very clear in sorting. For a practical example, sort the following list by creation time:

pages = [
{' title ': ' Ten Years ' Learning Program Design ', ' 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 encyclopedia ', ' 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 daquan ', ' 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 name as an 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 (2) = = False.

Then, call the Sort method on pages:

Pages.sort (key=lambda item:item[' index ')]

Here, I need to pass a function for the key that returns the value that needs to be compared.

Of course, you can also use the Itemgetter method provided by operator to get this value to be compared.

From operator Import Itemgetter
Names.sort (Key=itemgetter (' index '))

In addition to Itemgetter, the operator module also provides Attrgetter and Methodcaller.

Zhang He made some necessary Chinese commentaries to the aforementioned sorting mini-how to, which is essentially the same as the sorting.

If you want to know a little more, you can see


Sort a dictionary list with a keyword

Problem

You have a list of dictionaries, and you want to sort the list by one or several dictionary fields.


Solution

By using the Itemgetter function of the operator module, you can easily sort such a data structure. Suppose you retrieve a list of website membership information from the database and return it in 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}
]

It is easy to sort through any dictionary field to enter the result line, 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)

Produces 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 parameter. This parameter is the callable type and accepts a single element from rows, and then returns the value to be sorted. The Itemgetter () function is responsible for creating this callable object.

The Operator.itemgetter () function has an index parameter that is used by records in rows to find the value. 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 callable object it generates returns a tuple that contains 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, such as by first name and first name, in the example.

Itemgetter () can sometimes be substituted with a lambda expression, such as:

Rows_by_fname = sorted (rows, Key=lambda r:r[' fname '))
Rows_by_lfname = sorted (rows, Key=lambda r: (r[' lname '],r[' fname '))

This is also a good plan. However, using the Itemgetter () method will run a little faster. Therefore, if you have a higher performance requirement, 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}
>>>

The sort does not support native comparison objects.

Problem

You want to sort the same types of objects, but they do not support native comparison operations.


Solution

The built-in sorted () function has a keyword parameter key that can be passed to a callable object, which returns a value for each incoming object, which is sorted used to sort the objects. For example, if you have a user instance sequence in your application, and you want to sort by their user_id attributes, 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 personal preferences. However, the attrgetter () function usually runs faster, and can also allow multiple fields to be compared at the same time. This is similar to the Operator.itemgetter () function in the dictionary type (refer to section 1.13). For example, if the user instance also has a first_name and last_name attribute, you can sort the following:

By_name = sorted (Users, Key=attrgetter (' last_name ', ' first_name '))

Also 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)
>>>

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.