Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use ChainMap mutation in python

Shulou Source: shulou.com Published: 2022-06-03 15:34:00 09月18日 Update

This article mainly introduces how to use ChainMap mutation in python. It is very detailed and has a certain reference value. Friends who are interested must finish it!

1. ChainMap supports mutation. In other words, update, add, delete, and pop-up keys are allowed. In this case, these actions only apply to the first mapping.

> > from collections import ChainMap > numbers = {"one": 1, "two": 2} > letters = {"a": "A", "b": "B"} > alpha_num = ChainMap (numbers, letters) > alpha_numChainMap ({'one': 1,' two': 2}, {'one': 1,' two': 2}, {'axie:' approved, 'baked:' B'}) > > # Add a new key-value pair > > alpha_num ["c"] = "C" > > alpha_numChainMap ({'one': 1) 'two': 2,' two'::'C'}, {'one'::' baked:'B'}) > # Update an existing key > alpha_numChainMap ["b"] = "b" > alpha_numChainMap ({'one': 1,' two': 2,'C': 'one':,' baked:'b'}, {'ABA:' A') 'baked:' B'}) > > # Pop keys > alpha_num.pop ("two") 2 > alpha_num.pop ("a") Traceback (most recent call last):... KeyError: "Key not found in the first mapping:'a'" > > # Delete keys > del alpha_num ["c"] > alpha_numChainMap ({'one': 1,' baked:'b'}, {'aqu:' A') Del alpha_num ["a"] Traceback (most recent call last):. KeyError: "Key not found in the first mapping:'a'" > # Clear the dictionary > alpha_num.clear () > alpha_numChainMap ({}, {'a: 'Agar,' baked:'B'}))

2. Changing the contents of a given chain mapping only affects the first mapping, even if you try to change the keys in other mappings in the list.

You can use this behavior to create an updatable chain map without modifying the original input dictionary. In this case, you can use an empty dictionary as the first parameter of ChainMap.

> from collections import ChainMap > numbers = {"one": 1, "two": 2} > letters = {"a": "A", "b": "B"} > alpha_num = ChainMap ({}, numbers, letters) > alpha_numChainMap ({}, {'one': 1,' two': 2}, {'averse:' Aging, 'baking:' B'}) > > alpha_num ["comma"] = " "> alpha_num [" period "] =". "> alpha_numChainMap ({'comma':',', 'period':'.'}, {'one': 1,' two': 2}, {'one'::' Agar, 'baked:' B'}) these are all the contents of the article" how to use ChainMap mutations 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: Content dictionary situation article update original value function interest parameter guy partner in other words more knowledge industry behavior information information channel channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info Huawei macOS OPPO Reno