Python dictionary sorting ordereddict

Source: Internet
Author: User

In python2.7.x, ordereddict is added to the collections class. The usage is as follows:

 

pywugw@pywugw-laptop:~$
/usr/local/bin/python2.7
Python 2.7b1(r27b1:79927, Apr 26 2010, 11:44:19)
[GCC 4.4.3] on linux2
Type "help",
"copyright", "credits"
or "license"
for more information.
>>>
from collections import OrderedDict
>>> d
= {'banana': 3,
'apple':4,
'pear': 1,
'orange': 2}

# Sort by key
>>> Ordereddict (sorted (D. Items (),
Key = Lambda T: T [0])
Ordereddict ([('apple', 4 ),
('Banana ', 3 ),
('Orange ', 2 ),
('Pear ', 1)])

# Sort by value
>>> Ordereddict (sorted (D. Items (),
Key = Lambda T: T [1])
Ordereddict ([('pear ', 1 ),
('Orange ', 2 ),
('Banana ', 3 ),
('Apple', 4)])

# Sort by key length
>>> Ordereddict (sorted (D. Items (),
Key = Lambda T: Len (T [0])
Ordereddict ([('pear ', 1 ),
('Apple', 4 ),
('Orange ', 2 ),
('Banana ', 3)])

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.