如果值相同,如何在字典中对键排序?

时间:2018-08-30 05:45:29

标签: python-3.x

如果值相同,如何在字典中对键进行排序?

dictionary={}
count={'S': 28, 'O': 24, 'C': 20, 'W': 20, 'M': 17, 'T': 17, 'G': 17, 'K': 14, 'E': 11, 'N': 10, 'F': 8, 'D': 7, 'Y': 7, 'L': 6, 'I': 6, 'Q': 6, 'J': 5, 'A': 2, 'U': 2, 'V': 2, 'R': 2, 'Z': 1}
for key, value in sorted(count.items(),reverse=True, key=lambda item: (item[1], item[0])):
    #print ("%s: %s" % (key, value))
    dictionary[key] = value
print(dictionary)


OUTPUT:{'s': 28, 'o': 24, 'w': 20, 'c': 20, 't': 17, 'm': 17, 'g': 17, 'k': 14, 'e': 11, 'n': 10, 'f': 8, 'y': 7, 'd': 7, 'q': 6, 'l': 6, 'i': 6, 'j': 5, 'v': 2, 'u': 2, 'r': 2, 'a': 2, 'z': 1}


BUT i want like this:{'s': 28, 'o': 24, 'c': 20, 'w': 20, 'g': 17, 'm': 17, 't': 17, 'k': 14, 'e': 11, 'n': 10, 'f': 8, 'd': 7, 'y': 7, 'i': 6, 'l': 6, 'q': 6, 'j': 5, 'a': 2, 'r': 2, 'u': 2, 'v': 2, 'z': 1}

1 个答案:

答案 0 :(得分:1)

您可以通过取反而不是指定reverse=True来反转数字项目的顺序:

dictionary={}
count={'S': 28, 'O': 24, 'C': 20, 'W': 20, 'M': 17, 'T': 17, 'G': 17, 'K': 14, 'E': 11, 'N': 10, 'F': 8, 'D': 7, 'Y': 7, 'L': 6, 'I': 6, 'Q': 6, 'J': 5, 'A': 2, 'U': 2, 'V': 2, 'R': 2, 'Z': 1}
for key, value in sorted(count.items(), key=lambda item: (-item[1], item[0])):
    #print ("%s: %s" % (key, value))
    dictionary[key] = value
print(dictionary)

这将输出:

{'S': 28, 'O': 24, 'C': 20, 'W': 20, 'G': 17, 'M': 17, 'T': 17, 'K': 14, 'E': 11, 'N': 10, 'F': 8, 'D': 7, 'Y': 7, 'I': 6, 'L': 6, 'Q': 6, 'J': 5, 'A': 2, 'R': 2, 'U': 2, 'V': 2, 'Z': 1}