【Python】字典哈希表按键(key)值(value)顺序和逆序输出
生活随笔
收集整理的這篇文章主要介紹了
【Python】字典哈希表按键(key)值(value)顺序和逆序输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
按照鍵(key)排序
d = {'c':2, 'b':1, 'a':4, 'd':3} print(d)# 順序 for i in sorted (d) : print ((i, d[i]), end =" ") print('\n','順序如上,逆序如下')# 逆序 for i in sorted (d, reverse=1) : print ((i, d[i]), end =" ") # 輸出如下: # {'c': 2, 'b': 1, 'a': 4, 'd': 3} # ('a', 4) ('b', 1) ('c', 2) ('d', 3) # 順序如上,逆序如下 # ('d', 3) ('c', 2) ('b', 1) ('a', 4)按照值(value)排序
d = {'a':2, 'b':1, 'c':4, 'd':3} print(d)# 順序 out = sorted(d.items(), key=lambda item:item[1]) print(out)# 逆序 d = {'a':2, 'b':1, 'c':4, 'd':3} out = sorted(d.items(), key=lambda item:item[1], reverse=1) print(out)print(type(out), type(out[0]))# 輸出如下: # {'a': 2, 'b': 1, 'c': 4, 'd': 3} # [('b', 1), ('a', 2), ('d', 3), ('c', 4)] # [('c', 4), ('d', 3), ('a', 2), ('b', 1)] # <class 'list'> <class 'tuple'>注:
out = sorted(d.items(), key=lambda item:item[1], reverse=1)這句話有點難理解,可以分開來看:
- sorted 默認對對象進行升序排列
- 后面的 reverse=1 是指逆序排列
- d.items() 是把字典 d 轉成了可迭代對象
- lambda item:item[1] 是定義了一個匿名函數,輸入是 item 輸出是 item[0] ,也就是取出了字典中的 值
所以,總體意思就是按照字典中的 值 對字典進行排序
猜你喜歡:👇🏻
?【Python】字典(Dictionary) items()方法
?【Python】sort 和 sorted 的用法區別
?【Python】判斷字符串 str 是否為空
總結
以上是生活随笔為你收集整理的【Python】字典哈希表按键(key)值(value)顺序和逆序输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Leetcode】组合、排列、子集、切
- 下一篇: python线程池模块第三方包_pyth