# list of tuples with dynamic change in position

Peter Otten __peter__ at web.de
Tue Sep 7 09:16:30 CEST 2010

```sajuptpm wrote:

> More details
> I have a list of tuples l = [((cpu_util,mem_util),(disk_util)),
> ((cpu_util,mem_util),(disk_util))]
> ie, l = [((30,50),(70)), ((50,20),(20))]
>
> l.sort(key=lambda x:(-x[0][0], x[1][0])) # sorting cpu_util asc and
> disk_util desc
>
> suppose i changed order that is l = [((mem_util,cpu_util),
> (disk_util)), ((mem_util,cpu_util),(disk_util))]
> So i have to change the sort code to l.sort(key=lambda x:(-x[0][1],
> x[1][0])) # sorting cpu_util asc and disk_util desc
>
>
> I want to use same (common) sort code, that must work even if i
> changed tuple order.

Use namedtuples:

from collections import namedtuple

Pair = namedtuple("Pair", "pair disk_util")
A = namedtuple("A", "cpu_util mem_util")
B = namedtuple("B", "mem_util cpu_util")

# you can safely omit this step
for class_ in A, B, Pair:
del class_.__repr__

items = [((30,50), 70), ((50,20),20)]

a = [Pair(A(x, y), z) for (x, y), z in items]
b = [Pair(B(y, x), z) for (x, y), z in items]

def sort(items):
items.sort(key=lambda x: x.pair.mem_util, reverse=True)
items.sort(key=lambda x: x.pair.cpu_util)

sort(a)
print a

sort(b)
print b

Peter

```