python ChainMap如何实现字典操作

428次阅读
没有评论

python

1、ChainMap支持与常规字典相同的API访问现有密钥。可以用字典样式的键来搜索现有的键,或者可以用.get()。

>>> 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。

>>> 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电脑。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-08-06发表,共计745字。
新手QQ群:570568346,欢迎进群讨论 Python51学习