## Pages

Showing posts with label sorted(). Show all posts
Showing posts with label sorted(). Show all posts

## Saturday, May 16, 2009

### How to sort a Python tuple

Python tuple is immutable. Therefore, it cannot be changed.

To sort a Python tuple, we can create a new list using sorted() method.

If we still need it as a tuple, just apply tuple() to the new list.
>>> z = (1, 4, 3, 7, 2, 12, -3, 3)
>>> sorted_z = tuple(sorted(z))
>>> sorted_z
(-3, 1, 2, 3, 3, 4, 7, 12)

### How to sort a Python list

Suppose that you have a Python list,

[1, 4, 3, 7, 2, 12, -3, 3]

that needed to be sorted.

The list can be sorted by directly applying the sort() method to the list, and indirectly by using the sorted().

### Using sort()

The list will be sorted and the list will now become the new sorted list.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> y.sort()
>>> y
[-3, 1, 2, 3, 3, 4, 7, 12]

### Using sorted()

The list will be sorted as a new list.

We can create a new sorted list, and the original remains.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> sorted(y)
[-3, 1, 2, 3, 3, 4, 7, 12]
>>> y
[1, 4, 3, 7, 2, 12, -3, 3]

## Tuesday, February 24, 2009

### How to sort Python dictionary

To sort a Python dictionary, and append the keys into a list.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get)
['c', 'a', 'b']

To sort a Python dictionary, and append tuples of the key and value into a list.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]

To sort a Python dictionary, and append the keys into a tuple, and the values into a tuple.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> the_keys, the_vals = zip(*[(the_key, x[the_key])
for the_key in sorted(x, key=x.get)])
>>> the_keys
('c', 'a', 'b')
>>> the_vals
(1, 2, 3)

The results from the above examples are in ascending order. To sort in descending order, attach reverse=True at the end of the sorted() function.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get, reverse=True)
['b', 'a', 'c']