简体   繁体   English

Python 中的排序字典(AA 必须在 Z 之后)

[英]Sorting dictionary in Python (AA must come after Z)

mydict = {
    'Column A':'test',
    'Column S': 'NORMAL',
    'Column C': 'test',
    'Column AA': 'non-Gurantee',
    'Column Z': 'SAMPLE',
    'Column F': 'STANDARD'
}

Looking to sort this dictionary with AA coming after Z. Is this possible?希望用 Z 之后的 AA 对这本字典进行排序。这可能吗?

You need to sort the items in the dictionary according to the length of the keys (you didn't specify if this is what you are looking for but in addition, I also sorted them by lexical order) This should do the trick:您需要根据键的长度对字典中的项目进行排序(您没有指定这是否是您要查找的内容,但此外,我还按词汇顺序对它们进行了排序)这应该可以解决问题:

mydict  = {    'Column A':'test',
    'Column S': 'NORMAL',
    'Column C': 'test',
    'Column AA': 'non-Gurantee',
    'Column Z': 'SAMPLE',
    'Column F': 'STANDARD'
}
k = dict(sorted(mydict .items(),key=lambda x: (len(x[0]), x[0])))
print(k)

output: output:

{'Column A': 'test', 'Column C': 'test', 'Column F': 'STANDARD', 'Column S': 'NORMAL', 'Column Z': 'SAMPLE', 'Column AA': 'non-Gurantee'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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