TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Sort Examples: Sorted List, Dictionary

This Python 3 article focuses on sorting elements. It sorts a list, a dictionary and uses the sorted method with keys.

Sort. Everything is ordered.

Even a random sequence has an order, one based on its randomness. But often in programs, we use a sort method to order data from low to high, or high to low.

Ways to sort. In Python, we use sort and its friend sorted. We can sort a list. And sorted() returns a view (not a list) that is ordered. This simplifies things.

An example. Let us first reorder a list of integers. To order a list's elements from lowest to highest (starting with negative numbers, moving to positive ones), we call the sort() method.

Tip: The list is sorted in-place. Nothing needs to be assigned to the sort() call.

Based on:

Python 3

Python program that sorts list

# Contains unsorted, positive and negative integers.
elements = [100, 200, 0, -100]

# Sort from low to high.
elements.sort()
print(elements)

Output

[-100, 0, 100, 200]

Reverse. This operation inverts the order of the elements. We can apply the reversed() view to any iterable collection. Here, we apply reversed to the result of the sorted built-in method.

Then: We iterate over the reversed view with a for-loop. Reversed returns an iterator, not a list.

Warning: You can actually apply a reversed sort directly with the sorted keyword. Simply set the "reverse" argument to True.

Python program that uses reversed, sorted

elements = [22, 333, 0, -22, 1000]

# Use a reversed, sorted view: a descending view.
view = reversed(sorted(elements))

# Display our results.
for element in view:
    print(element)

Output

1000
333
22
0
-22

Sorted. This built-in can receive more than one argument. The first is the collection we want to sort. But we also can specify a key function.

Key: This is a function that receives an element, and returns a value that is used to sort.

Tip: A lambda expression may be used for the key argument. Here we receive an argument with name "color," and return its length.

Reverse: We can specify that the collection is to be sorted in descending order (from high to low) by setting reverse to true.

Python program that uses sorted, key, reverse

# An array of color names.
colors = ["blue", "lavender", "red", "yellow"]

# Sort colors by length, in reverse (descending) order.
for color in sorted(colors, key=lambda color: len(color), reverse=True):
    print(color)

Output

lavender
yellow
blue
red

Sort keys. How can you sort the keys in a dictionary? First you must acquire a list of the keys using the keys() method. Then, you can use the sorted built-in to order those keys.

Note: This approach requires a lookup to get the values from the sorted key view. Another approach may be faster.

Python program that sorts dictionary keys

# A dictionary with three pairs.
furniture = {"table": 1, "chair": 2, "desk": 4}

# Get sorted view of the keys.
s = sorted(furniture.keys())

# Display the sorted keys.
for key in s:
    print(key, furniture[key])

Output

chair 2
desk 4
table 1

Error. An error will occur if you try to sort the result of the keys() method. This is because keys does not return a list. It returns a dict_keys object.

So: We have to use sorted() here to avoid further conversions. We are not actually dealing with lists.

However: If the program has to repeatedly get the keys and sort them, using a cached list of the sorted keys would likely be faster.

Error from calling sort on keys:

AttributeError: 'dict_keys' object has no attribute 'sort'

Objects. A list of class instances (objects) can be sorted. Here we introduce the Bird class. Each Bird has a weight. And the repr method returns a string representation of each object.

Append: We append three new Bird objects to our list. The Birds are not ordered by their weights when we add them.

Sort: We use the sort() method with a lambda "key" argument. The lambda selects the key that each Bird is sorted upon.

Finally: We display the sorted list of birds. This approach can be used with any object type.

Python program that sorts list of objects

class Bird:
    def __init__(self, weight):
        self.__weight = weight

    def weight(self):
        return self.__weight

    def __repr__(self):
        return "Bird, weight = " + str(self.__weight)

# Create a list of Bird objects.
birds = []
birds.append(Bird(10))
birds.append(Bird(5))
birds.append(Bird(200))

# Sort the birds by their weights.
birds.sort(lambda b: b.weight())

# Display sorted birds.
for b in birds:
    print(b)

Output

Bird, weight = 5
Bird, weight = 10
Bird, weight = 200

Performance. I benchmarked the sort() and reverse() methods, and compare them to the sorted() and reversed() views. I found that the sort and reverse methods were more efficient here.

Warning: This benchmark is flawed. The sort and reverse methods change the actual list ordering.

However: The results show that using sorted() and reversed() views is not always a performance advantage.

Info: The sorted() built-in actually copies the data into a new list according to the documentation.

Return a new sorted list from the items in iterable.

Sorted: Python.org

Python program that benchmarks sorted, reversed

import time

data = ["carrot", "apple", "peach", "nectarine"]

print(time.time())

# Version 1: use sort and reverse.
i = 0
while i < 1000000:
    v = 0
    data.sort()
    for element in data:
        v += 1
    data.reverse()
    for element in data:
        v += 1
    i += 1

print(time.time())

# Version 2: use sorted and reversed.
i = 0
while i < 1000000:
    v = 0
    for element in sorted(data):
        v += 1
    for element in reversed(data):
        v += 1
    i += 1

print(time.time())

Output

1389905688.967582
1389905691.0347     Call sort(), reverse():    2.07 s
1389905693.901864   Call sorted(), reversed(): 2.87 s

String chars. We can sort the characters in a string. We first convert the string to a list of characters with a list comprehension. Then, after sort(), we join the chars together.

Convert: String, chars

Python that sorts string chars

value = "boat"

# Get list comprehension of characters and sort the list.
list = [c for c in value]
list.sort()

# Join the characters together.
result = "".join(list)
print(result)

Output

abot

Custom. The data structures we construct before sorting are important. For example, building a list of tuples, and then sorting on an item in each tuple, is effective.

Files sizes: We sort files by their sizes. We store each file and its size to a tuple, and then append that tuple to a list.

Sort Files, Size

A summary. Usually the fastest and simplest way to deal with data is not to sort it. But often we need to sort. It helps organize data in memory and is helpful for writing data to a file.

In Python, we can directly use sort, or use the sorted() view. Where possible, using sort() is faster because it copies less. But often the simplest solution is preferred.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf