Python dict字典 按key或value 排序

Python Dict Sorted

Posted by BlueFat on Thursday, August 11, 2022
# sorted默认按key排序 
>>> A = {'a':6,'b':4,'c':3}
>>> sorted(A)
['a', 'b', 'c']

>>> sorted(A.values())
[3, 4, 6]

# sorted按key排序
>>> sorted(A.items(), key=lambda v: v[0])

# sorted按value排序
>>> sorted(A.items(), key=lambda v: v[1])
[('c', 3), ('b', 4), ('a', 6)]

# 获得排序的第一个元组 
>>> sorted(A.items(), key=lambda v: v[1])[0]
('c', 3)
>>> sorted(A.items(), key=lambda v: v[1])[0][0]
'c'
>>> 
>>> sorted(A.items(), key=lambda v: v[1])[0][1]
3