
1、ChainMap支持与常规字典相同的API访问现有密钥。可以用字典样式的键来搜索现有的键,或者可以用.get()。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | >>> from collections import ChainMap
>>> 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 (most recent call last):
...
KeyError: 'three'
|
2、在搜索目标链映射中搜索所有映射,直到找到所需的键。
如果密钥不存在,您将获得通常的KeyError。
1 2 3 4 5 6 7 8 9 10 11 12 | >>> from collections import ChainMap
>>> 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实现字典操作的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。