The python dictionary is sorted by value
d = {'a': 1, 'b': 4, 'c': 2, 'f': 12}
d = {'a': 1, 'b': 4, 'c': 2, 'f' : 12}
# 第一種方法,key使用lambda匿名函數取value進行Sort
a = sorted(d.items(), key=lambda x: x[1])
a1 = sorted(d.items(),key = lambda x:x[1],reverse = True)
print(a)
print(a1)
The print result is:
[('a', 1), ('c', 2), ('b', 4), ('f', 12)]
[('f', 12), ('b', 4), ('c', 2), ('a', 1)]
# key is sorted by key using lambda anonymous function
a2 = sorted(d.items(),key = lambda x:x[0])
print(a2)
Result: [('a', 1), ('b', 4), ('c', 2), ('f', 12)]
# The second method uses the operator's itemgetter for sorting
import operator
b = sorted(d.items(), key=operator.itemgetter(1))
print(b)
Result: [('a', 1), ('c', 2), ('b', 4), ('f', 12)]
# The third method is that the keys and values are divided into tuples, and sorting is performed.
f = zip(d.keys(), d.values())
c = sorted(f)
print(c)
Result: [('a', 1), ('b', 4), ('c', 2), ('f', 12)]
This is a very rude operation:
l = input()
d = {}
for i in l:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
# sorted(d, key=lambda x: (-x[1], x[0]), reverse=False)
for k, v in sorted(d.items(), key=lambda x: (-x[1], x[0]), reverse=False):
print(k, end='')
x[1] represents the value of the dictionary (that is, the statistical number of each letter),
-x[1] represents the inverse of the dictionary value;
The default sorted is ascending order, from small to large, -3 -2 -1 0 1 2 like this.
The reverse here is a bit superfluous.Not necessary.
# The default is ascending order. First, sort the values of the dictionary in ascending order. If the same number is encountered, sort the keys of the dictionary in ascending order.
ans1 = sorted(ansDic.items(),key = lambda x:(-x[1], x[0]))