Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Dictionary Operation by ChainMap in python

Shulou Source: shulou.com Published: 2022-06-03 15:34:01 11月14日 Update

This article mainly introduces the python ChainMap how to achieve dictionary operation, the article is very detailed, has a certain reference value, interested friends must read it!

1. ChainMap supports the same API access to existing keys as regular dictionaries. You can use dictionary-style keys to search for existing keys, or you can use .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. Search for all mappings in the search target chain map until you find the desired key.

If the key does not exist, you will get the usual 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 is all the contents of this article "how to operate ChainMap in python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Dictionary search content key article same value interest guy partner general more style goal knowledge industry information channel channel reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Shulou Tech Info Apple Shulou Technology