
Python 代碼閱讀合集介紹:為什么不推薦Python初學者直接看項目源碼
本篇閱讀的代碼根據給定選擇器定義的查詢結構(路徑),獲取嵌套字典中對應的鍵值。
本篇閱讀的代碼片段來自于30-seconds-of-python。
get
from functools import reduce
from operator import getitem
def get(d, selectors):
return reduce(getitem, selectors, d)
# EXAMPLES
users = {
'freddy': {
'name': {
'first': 'fred',
'last': 'smith'
},
'postIds': [1, 2, 3]
}
}
get(users, ['freddy', 'name', 'last']) # 'smith'
get(users, ['freddy', 'postIds', 1]) # 2
get函數接收一個字典d,和一個選擇器(列表形式)selectors,返回由選擇器指定的路徑的鍵的值。
函數使用reduce函數在選擇器上逐一使用operator.getitem(a, b)函數,選擇器元素的指示,逐一獲取嵌套的子字典結構(或最終值)。
operator模塊提供了一套與Python的內置運算符對應的高效率函數。例如,operator.add(x, y)與表達式x+y相同,operator.getitem(a, b)則是返回a上面索引為b的值。
reduce(getitem, selectors, d)函數將getitem()累計的作用于selectors的元素上,并將d做為左邊參數的初始值參與第一次getitem的調用。例如reduce(getitem, [a, b, c], d)是計算getitem(getitem(getitem(d, a), b), c)。也就是從輸入字典開始,不斷的根據key來獲取對應的子字典(或最終值)。