Reputation: 413
I have a dict that I want to use as the key for sorting a list.
names = {'a': 1, 'b': 0, 'c': 2, 'd': 3, 'e': 4, 'f': 5,}
nodes = {'0': 'b', '1': 'a', '2': 'c', '3': 'd', '4': 'e', '5': 'f'}
l1 = [0, 1, 2, 3, 4]
l1.sort(key=names.get)
What I want is L1 to be [1, 0, 2, 3, 4]
.
Obviously the sort line doesn't work as the numbers aren't proper keys for the dict.
I've got the nodes, so my thought is to convert L1 into string values, use the resulting string as the key for the sort, but I just don't know how to do that.
I could do this in some sort of mega loop, but i'm trying to learn python and i'm sure there is a more pythonic way to do it.
Upvotes: 1
Views: 55
Reputation: 214957
You can write a lambda expression as key:
l1.sort(key=lambda x: nodes.get(str(x))) # convert the int to str here
l1
# [1, 0, 2, 3, 4]
Upvotes: 3