程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python dictionary sorted by value sorted

編輯:Python

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]))


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved