Home > Backend Development > Python Tutorial > Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

WBOY
Release: 2023-04-11 15:04:03
forward
1457 people have browsed it

Preface

A collection is a specialized container data type (Container Datatype) that can replace Python's general built-in containers, such as dict, list, set, and tuple. A container is a special purpose object that can be used to store different objects. It provides a way to access the contained objects and iterate over them.

Python provides the collections module that implements container data types. In this series of chapters, we will learn about the different types of collection harmonies in the Collections module, including:

  • ChainMap
  • Counter
  • Deque
  • DefaultDict
  • NamedTuple
  • OrderedDict
  • UserDict
  • UserList
  • UserString

The following are introduced separately. These container types - ChainMap.

Understanding ChainMap

The ChainMap class (called the chain mapping class) provided by Python is a dictionary-like class that is used to quickly link many mappings so that they can be Processed as a single unit. It's usually much faster than creating a new dictionary and running multiple update() calls.

The syntax format is as follows:

xchainMap = collections.ChainMap(*maps)

Explanation: collections in the syntax format are imported completion modules name. If you import the module like this: import collections as cts, the syntax can be changed to: class cts.ChainMap(*maps), or fuzzy import: from collections import ChainMap, which can be modified to: ChainMap(*maps).

ChainMap can combine multiple dictionaries or other mappings to create a single, updateable view (list of dictionaries). If no mapping is specified, an empty dictionary is provided so that new chain maps (ChainMap) always have at least one mapping available.

The underlying mapping of the chain mapping is stored in a list. The list is public and can be accessed or updated using the maps property. Apart from the maps attribute, chain mapping has no other new extended state.

ChainMap merges underlying mappings by reference. So if one of the underlying maps gets updated, those changes will be reflected in the ChainMap as well.

Chain mapping supports all common dictionary (dict) methods. In addition, there is a maps attribute for methods that create new subcontexts, and the attribute maps can be used to access all maps except the first map - maps is a list.

corresponds to a user-updatable mapping list, which is ordered from the first search to the last search. It is the only stored state that can be modified to change the mapping to be searched. Such a list should always contain at least one mapping.

Let’s look at the following simple example. The code list is as follows:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

The output result of running the program is as follows:

ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
[{'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'}]
Copy after login

In the above list, we Define a ChainMap object (chain_map) with two dictionaries. Then we print out the ChainMap object and maps property. As you can see in the output, the result is a view of the composition of these dictionaries.

Accessing the key values ​​of ChainMap

We can access the keys and values ​​of ChainMap by using the keys() and values() methods. The code example is as follows:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

The output result of the above code is:

KeysView(ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'}))
ValuesView(ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'}))
Copy after login

As shown in the program output result, the result of chain_map.keys() is a KeysView ( key view), the result of chain_map.values() is a ValuesView (value view). These two view type built-in classes are iterable objects that can traverse the corresponding key names and value objects respectively. For example:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

The output result is:

key = a,value=A
key = b,value=B
key = one,value=1
key = two,value=2
链映射包含的值为:
A;B;1;2;
Copy after login

Combining the code and output results, it is easy to understand, that is, chain mapping is to combine multiple mappings (map has Many implementations (dictionary is one of them) are packaged into a map, that is, a chain map, and can then be accessed like a dictionary. For example, you can access the value of a certain key like a dictionary:

print(chain_map['b'] )
Copy after login

That is, use the key name: chain_map[' one '] to access the value of a single item in the underlying dictionary of ChainMap.

Add new mapping to ChainMap

ChainMap can contain any number of dictionaries. We add a new dictionary to the ChainMap using the built-in new_child() method. The new_child() method returns a new ChainMap containing the new mapping, followed by all mappings in the current instance. One thing to note here is that the newly added dictionary will be placed at the beginning of the ChainMap. Let’s look at the example:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

# Run the program and the input result is as follows:

Old: ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
New: ChainMap({'x': 0, 'y': 1}, {'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
Copy after login

这里需要注意的是,用链式映射的new_child()方法添加新字典后,不改变原来的链映射,会返回一个新的ChainMap对象。另外,如果你修改链式映射所包含的映射或字典,变化也将体现在链式映射对象中。

另外,实践中要当心:如果你按照字典操作来添加新的键值对,则该键值对会添加到链式映射所包含的第一个映射中,如:new_chain_map['X'] = 'Unkown' 。自己动手试试看。

所含映射有相同键怎么办?

底层上,链式映射主要是为把多个字典或映射打包成一个映射,以便集中操作。如果所办函的字典中有相同的键会怎样呢?来看示例:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

运行程序输出结果如下:

ChainMap({'id': 21001, 'country': '大秦', 'emperor': '嬴政'}, {'name': '李靖', 'country': '大唐', 'title': '元帅'})
大秦
('name', '李靖')
('country', '大秦')
('title', '元帅')
('id', 21001)
('emperor', '嬴政')
Copy after login

很显然,链接的映射中出现相同字典项时,只读取第一个,以第一个为准,而且当你更新一个键的值时,它也只是更新第一个映射内容的键值。

如果你想一次更新所有映射中的相同键的值怎么办呢?你可以自定义一个ChainMap子类来实现,或定义更新方法。因为ChainMap中有个属性maps持有完整的各个映射,可以基于此属性来完成相同键的一次性更新。这里简单给个通过方法的方式实现多映射相同键的一次更新。示例代码如下:

Python programming: Another way to use dictionary chain mapping (ChainMap), play it!

当然,你可以写得更复杂一点,以完成更多的需要,也可实现一次多个映射中的相同键的值。自己动手试试吧。

本文小结

本文主要介绍了Python集合模块中的链式映射容器——ChainMap的使用,可以把多个字典打包成一个对象来操作。同时需要注意的是,该映射只是对原字典的引用,当你修改原字典时,相应的变化也为体现在链式映射中。同时,在为ChainMap新增新的键值对时,它会添加到所包含的第一个映射对象中。

The above is the detailed content of Python programming: Another way to use dictionary chain mapping (ChainMap), play it!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template