Sorting a list of tuples by a certain element in a tuple

697 views Asked by At
def insert(key, value, D, hasher = hash):

    x = hash(key)
    key_value = (x, key, value)
    D.append(key_value)
    sorted(D, key = lambda x:x[0])
    return D

insert("swag", 100, D, hash)

insert("swg", 150, D, hash)

print(D)

this never seems to be sorted,

I want to sort the list via the x value

2

There are 2 answers

2
Moses Koledoye On

You are sorting the list and immediately throwing the sorted list away. Note that sorted returns a new list so you'll also need to reassign the sorted list to the name D.

...
return sorted(D, key=lambda x:x[0])

To sort in-place, use the sort method of the list: D.sort

def insert(key, value, D, hasher = hash):
    ...
    D.sort(key=lambda x:x[0])
3
Prune On

You've confused sorted and sort. sorted is a function that leaves the original iterable alone, but returns a sorted item. You didn't save that value. Try this:

return sorted(D, key = lambda x:x[0])

EXAMPLE

def insert(key, value, D, hasher = hash):

    x = hash(key)
    key_value = (x, key, value)
    D.append(key_value)
    print D
    D.sort()
    return D


D = []
insert("swag", 100, D, hash)
insert("swg",  150, D, hash)
insert("loot", 200, D, hash)
insert("crud",  50, D, hash)

print(D)

Output:

[(-1840385907632881630, 'swag', 100)]
[(-1840385907632881630, 'swag', 100), (-369175422006790866, 'swg', 150)]
[(-1840385907632881630, 'swag', 100), (-369175422006790866, 'swg', 150), (5971043325587305850, 'loot', 200)]
[(-1840385907632881630, 'swag', 100), (-369175422006790866, 'swg', 150), (5971043325587305850, 'loot', 200), (5473401298224946764, 'crud', 50)]
[(-1840385907632881630, 'swag', 100), (-369175422006790866, 'swg', 150), (5473401298224946764, 'crud', 50), (5971043325587305850, 'loot', 200)]