Python Tricks - Dictionary Tricks(1)

Sorting Dictionaries for Fun and Profit

Python dictionaries don’t have an inherent order. You can iterate over them just fine but there’s no guarantee that iteration returns the dictionary’s elements in any particular order (although this is changing with Python 3.6).
意思就是字典是亂序的

However, it’s frequently useful to get a sorted representation of a dictionary to put the dictionary’s items into an arbitrary order based on their key, value, or some other derived property. Suppose you have a dictionary xs with the following key/value pairs:

>>> xs = {'a': 4, 'c': 2, 'b': 3, 'd': 1}

To get a sorted list of the key/value pairs in this dictionary, you could use the dictionary’s items() method and then sort the resulting sequence in a second pass:

 >>> sorted(xs.items())
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]

The key/value tuples are ordered using Python’s standard lexicographical ordering for comparing sequences.

To compare two tuples, Python compares the items stored at index zero first. If they differ, this defines the outcome of the comparison. If they’re equal, the next two items at index one are compared, and so on.

Now, because we took these tuples from a dictionary, all of the former dictionary keys at index zero in each tuple are unique. Therefore, there are no ties to break here.
在比較元組的時候我們是從序列的第一項開始進行比較的询张,如果第一項就不同那么我們就得出了相應的結果师坎,如果第一項相同那么我們就比較第二項膏秫,以此類推。但是字典因為鍵之間各不相同供搀,所以我們直接在第一項就可以區(qū)分出來。

In some cases a lexicographical ordering might be exactly what you want. In other cases you might want to sort a dictionary by value instead.
也許你想按照值來對字典的內(nèi)容進行排序蜂挪。

Luckily, there’s a way you can get complete control over how items are ordered. You can control the ordering by passing a key func to sorted() that will change how dictionary items are compared.

A key func is simply a normal Python function to be called on each element prior to making comparisons. The key func gets a dictionary item as its input and returns the desired “key” for the sort order comparisons.

Unfortunately, the word “key” is used in two contexts simultaneously here—the key func doesn’t deal with dictionary keys, it merely maps each input item to an arbitrary comparison key.

Now, maybe we should look at an example. Trust me, key funcs will be much easier to understand once you see some real code.

Let’s say you wanted to get a sorted representation of a dictionary based on its values. To get this result you could use the following key func which returns the value of each key/value pair by looking up the second element in the tuple:

 >>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

See how the resulting list of key/value pairs is now sorted by the values stored in the original dictionary? It’s worth spending some time wrapping your head around how key funcs work. It’s a powerful concept that you can apply in all kinds of Python contexts.
就是我們根據(jù)我們的需要對sorted的key值進行設定蛾茉,這樣我們就可以根據(jù)自己的需要對值進行排序。

In fact, the concept is so common that Python’s standard library includes the operator module. This module implements some of the most frequently used key funcs as plug-and-play building blocks, like operator.itemgetter and operator.attrgetter.

Here’s an example of how you might replace the lambda-based index lookup in the first example with operator.itemgetter:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1)) 
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Using the operator module might communicate your code’s intent more clearly in some cases. On the other hand, using a simple lambda expression might be just as readable and more explicit. In this particular case, I actually prefer the lambda expression.

Another benefit of using lambdas as a custom key func is that you get to control the sort order in much finer detail. For example, you could sort a dictionary based on the absolute numeric value of each value stored in it:

>>> sorted(xs.items(), key=lambda x: abs(x[1]))

If you need to reverse the sort order so that larger values go first, you can use the reverse=True keyword argument when calling sorted():

>>> sorted(xs.items(), key=lambda x: x[1],reverse=True)
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]

Like I said earlier, it’s totally worth spending some time getting a good grip on how key funcs work in Python. They provide you with a ton of flexibility and can often save you from writing code to transform one data structure into another.

Key Takeaways
  • When creating sorted “views” of dictionaries and other collections, you can influence the sort order with a key func.
  • Key funcs are an important concept in Python. The most frequently used ones were even added to the operator module in the standard library.
  • Functions are first-class citizens in Python. This is a powerful feature you’ll find used everywhere in the language.
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末姑躲,一起剝皮案震驚了整個濱河市欲侮,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌肋联,老刑警劉巖威蕉,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異橄仍,居然都是意外死亡韧涨,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門侮繁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來虑粥,“玉大人,你說我怎么就攤上這事宪哩∶浯” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵锁孟,是天一觀的道長彬祖。 經(jīng)常有香客問我,道長品抽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任圆恤,我火速辦了婚禮突倍,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己羽历,他們只是感情好焊虏,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著秕磷,像睡著了一般诵闭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上跳夭,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天涂圆,我揣著相機與錄音,去河邊找鬼币叹。 笑死润歉,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的颈抚。 我是一名探鬼主播踩衩,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼贩汉!你這毒婦竟也來了驱富?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤匹舞,失蹤者是張志新(化名)和其女友劉穎褐鸥,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體赐稽,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡叫榕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了姊舵。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晰绎。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖括丁,靈堂內(nèi)的尸體忽然破棺而出荞下,到底是詐尸還是另有隱情,我是刑警寧澤史飞,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布尖昏,位于F島的核電站,受9級特大地震影響祸憋,放射性物質(zhì)發(fā)生泄漏会宪。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一蚯窥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦拦赠、人聲如沸巍沙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽句携。三九已至,卻和暖如春允乐,著一層夾襖步出監(jiān)牢的瞬間矮嫉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工牍疏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蠢笋,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓鳞陨,卻偏偏與公主長得像昨寞,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子厦滤,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,505評論 0 23
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,456評論 0 13
  • 清澈援岩,透明,抓不住 時冷掏导,時暖享怀,摸不清 我羨慕著那種自由的流動 不受拘束的,不屬于任何人的 日復一日趟咆,年復一年 越...
    半紗朦朧閱讀 169評論 2 5
  • 讀小說 是我一直堅持的 最初添瓷,都是些俗套的網(wǎng)絡小說 直到現(xiàn)在依舊會讀 但現(xiàn)在多了一些名著小說而已 且甚是喜歡紙質(zhì)書...
    不會讀書的魚閱讀 133評論 0 1