說明
1、ChainMap的主要用例是提供一種有效的方法來管理多個(gè)范圍或上下文,并處理重復(fù)鍵的訪問優(yōu)先級。
2、當(dāng)有多個(gè)存儲重復(fù)鍵的字典訪問它們的順序時(shí),這個(gè)功能非常有用。
在ChainMap文檔中找到一個(gè)經(jīng)典的例子,它模擬Python如何分析不同命名空間中的變量名稱。
當(dāng)Python搜索名稱時(shí),它會依次搜索當(dāng)?shù)?、全局和?nèi)置的功能域,直到找到目標(biāo)名稱。Python作用域是將名稱映射到對象的字典。
為了模擬Python的內(nèi)部搜索鏈,可以使用鏈映射。
實(shí)例
>>> import builtins
>>> # Shadow input with a global name
>>> input = 42
>>> pylookup = ChainMap(locals(), globals(), vars(builtins))
>>> # Retrieve input from the global namespace
>>> pylookup["input"]
42
>>> # Remove input from the global namespace
>>> del globals()["input"]
>>> # Retrieve input from the builtins namespace
>>> pylookup["input"]
built-in function input>
知識點(diǎn)擴(kuò)展:
ChainMap類管理的是一個(gè)字典序列,并按其出現(xiàn)的順序搜索以查找與鍵關(guān)聯(lián)的值。ChainMap提供了一個(gè)很好的“上下文”容器,因此可以把它看成一個(gè)棧,棧增長時(shí)發(fā)生變更,棧收縮時(shí)這些變更被丟棄。
下面,我們來看看其基本的使用規(guī)則:
import collections
a = {"a": "A", "c": "c", }
b = {"b": "B", "c": "D", }
col = collections.ChainMap(a, b)
# 和普通字典一樣訪問
print(col["a"])
print(list(col.keys()), list(col.values()))
for key, value in col.items():
print(key, value)
可以看到,在相同的key值情況下,只有子映射a的值。這也就是說明ChainMap是按子映射傳遞到構(gòu)造函數(shù)的順序來搜索這些子映射。
以上就是python ChainMap管理用法實(shí)例講解的詳細(xì)內(nèi)容,更多關(guān)于python ChainMap的管理用法的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- Python實(shí)現(xiàn)字典序列ChainMap
- 在Python中合并字典模塊ChainMap的隱藏坑【推薦】
- python ChainMap的使用和說明詳解
- python ChainMap 合并字典的實(shí)現(xiàn)步驟