[英]sorting keys of a dictionary with lowercase letters, uppercase letters and numbers
I want to sort the keys of a dictionary first by numbers then lowercase letters and then uppercase letter and return it back in a dictionary with the correct value for the key.我想先按数字然后小写字母然后大写字母对字典的键进行排序,然后将其返回到字典中并使用正确的键值。 I came up with this, but in my opinion this is too long.
我想出了这个,但在我看来这太长了。 (board is the given dictionary you want to sort) board example :
(board 是您要排序的给定字典)board 示例:
board = {
(3, 4) : 0,
("a", 4) : 0,
(1, 3) : 0,
("X", 5) : 5,
("X", 1) : 1
}
My question is if it is possible to shorten the code.我的问题是是否可以缩短代码。
x = []
y = []
for k in dict.keys(board):
if str(k[0]).islower():
list.append(x, (k, board[k]))
for k in dict.keys(board):
if k[0] == "X":
list.append(y, (k, board[k]))
for k in range(0, len(x)):
del board[x[k][0]]
for k in range(0, len(y)):
del board[y[k][0]]
x = sorted(x)
y = sorted(y)
for k in range(0, len(x)):
board[x[k][0]] = x[k][1]
for k in range(0, len(y)):
board[y[k][0]] = y[k][1]
Following sort based in desired order but based upon the key tuple.按照所需顺序进行排序,但基于关键元组。
Thus ('X', 1) should be before ('X', 5) because first elements are equal so depends on second element.因此 ('X', 1) 应该在 ('X', 5) 之前,因为第一个元素是相等的,所以取决于第二个元素。
Sort Routine排序例程
def sort_dict(d):
def ordering(i):
"""Create ordering so that numbers are before strings
lowercase strings are before upper case strings"""
return ([isinstance(i, int), isinstance(i, str) and i.islower(), isinstance(i, str) and i.isupper()].index(True), i)
# By applying ordering to all elements of key, we create a new tuple
# which allows us to compare
return dict(sorted(d.items(), key=lambda kv: tuple(map(ordering, kv[0]))))
Test测试
board = {(3,4):0,("a",4):0,(1,3):0,("X",5):5,("X",1):1}
print(sort_dict(board))
Output输出
{(1, 3): 0, (3, 4): 0, ('a', 4): 0, ('X', 1): 1, ('X', 5): 5}
You can maybe do something like this:你也许可以做这样的事情:
result = {}
for x in sorted(filter(lambda x: type(x[0]) == int, board.keys())):
result[x] = board[x]
for x in sorted(filter(lambda x: type(x[0]) == str, board.keys()), key=lambda x: x[0].islower(), reverse=True):
result[x] = board[x]
>>> result
{(1, 3): 0, (3, 4): 0, ('a', 4): 0, ('X', 5): 5, ('X', 1): 1}
Also, just in case if you wanted to have uppercase letters before lowercase and if the numbers were only 1 digit long then you could have used ord to sort them另外,以防万一,如果您想在小写字母之前使用大写字母并且数字只有 1 位长,那么您可以使用ord对它们进行排序
>>>sorted(board.keys(), key=lambda x: ord(str(x[0])) if type(x[0]) == int else ord(x[0]))
[(1, 3), (3, 4), ('X', 5), ('X', 1), ('a', 4)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.