[英]How can I sort a dictionary by value in alphanumeric order with Python?
Im having a problem while sorting my dictionary with alphanumeric values.我在用字母数字值对字典进行排序时遇到问题。 Each value has at least one letter in front (sometimes two) followed by some numbers.每个值的前面至少有一个字母(有时是两个),后跟一些数字。 Example:例子:
shoppingList = {'milk': 'W30', 'eggs': 'W29', 'tuna': 'W3', 'gum': 'CL24', 'beans': 'W6'}
When Im sorting it:当我对它进行排序时:
sorted_dict = sorted(shoppingList.items(), key = operator.itemgetter(1))
for i in sorted_dict:
print(i)
Output:输出:
('gum', 'CL24')
('eggs', 'W29')
('tuna', 'W3')
('milk', 'W30')
('beans', 'W6')
So it seems the sort is only using the first number it comes across.所以看起来排序只使用它遇到的第一个数字。 Is there a way to get the output as有没有办法得到输出
('gum', 'CL24')
('tuna', 'W3')
('beans', 'W6')
('eggs', 'W29')
('milk', 'W30')
Thank you in advance.先感谢您。
Its sorting strings, not numbers, you need to parse the integer.它的排序字符串,而不是数字,你需要解析整数。
The one line approach would be ugly, so i'd be tempted to convert the given key below into a seperate function that can handle the splitting of the list单行方法会很丑,所以我很想将下面给定的键转换为一个单独的函数,可以处理列表的拆分
sorted(
shoppingList.items(),
key=lambda k: (
''.join(x for x in k[1] if not x.isdigit()),
int(''.join(x for x in k[1] if x.isdigit()))
)
)
[('gum', 'CL24'), ('tuna', 'W3'), ('beans', 'W6'), ('eggs', 'W29'), ('milk', 'W30')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.