简体   繁体   中英

Convert list of ints to strings as key for dict in sort

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM