1、ChainMap支持与常规字典相同的API访问现有密钥。可以用字典样式的键来搜索现有的键,或者可以用.get()。
>>>fromcollectionsimportChainMap >>>numbers={"one":1,"two":2} >>>letters={"a":"A","b":"B"} >>>alpha_num=ChainMap(numbers,letters) >>>alpha_num["two"] 2 >>>alpha_num.get("a") 'A' >>>alpha_num["three"] Traceback(mostrecentcalllast): ... KeyError:'three'
2、在搜索目标链映射中搜索所有映射,直到找到所需的键。
如果密钥不存在,您将获得通常的KeyError。
>>>fromcollectionsimportChainMap >>>for_adoption={"dogs":10,"cats":7,"pythons":3} >>>vet_treatment={"dogs":4,"cats":3,"turtles":1} >>>pets=ChainMap(for_adoption,vet_treatment) >>>pets["dogs"] 10 >>>pets.get("cats") 7 >>>pets["turtles"] 1
以上就是python ChainMap实现字典操作的方法,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
下一篇