


Python programming: Another way to use dictionary chain mapping (ChainMap), play it!
Apr 11, 2023 pm 03:04 PMPreface
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:
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'}]
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:
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'}))
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:
The output result is:
key = a,value=A key = b,value=B key = one,value=1 key = two,value=2 鏈映射包含的值為: A;B;1;2;
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'] )
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:
# 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'})
這里需要注意的是,用鏈?zhǔn)接成涞膎ew_child()方法添加新字典后,不改變原來的鏈映射,會返回一個新的ChainMap對象。另外,如果你修改鏈?zhǔn)接成渌挠成浠蜃值?,變化也將體現(xiàn)在鏈?zhǔn)接成鋵ο笾小?/p>
另外,實踐中要當(dāng)心:如果你按照字典操作來添加新的鍵值對,則該鍵值對會添加到鏈?zhǔn)接成渌牡谝粋€映射中,如:new_chain_map['X'] = 'Unkown' 。自己動手試試看。
所含映射有相同鍵怎么辦?
底層上,鏈?zhǔn)接成渲饕菫榘讯鄠€字典或映射打包成一個映射,以便集中操作。如果所辦函的字典中有相同的鍵會怎樣呢?來看示例:
運行程序輸出結(jié)果如下:
ChainMap({'id': 21001, 'country': '大秦', 'emperor': '嬴政'}, {'name': '李靖', 'country': '大唐', 'title': '元帥'}) 大秦 ('name', '李靖') ('country', '大秦') ('title', '元帥') ('id', 21001) ('emperor', '嬴政')
很顯然,鏈接的映射中出現(xiàn)相同字典項時,只讀取第一個,以第一個為準(zhǔn),而且當(dāng)你更新一個鍵的值時,它也只是更新第一個映射內(nèi)容的鍵值。
如果你想一次更新所有映射中的相同鍵的值怎么辦呢?你可以自定義一個ChainMap子類來實現(xiàn),或定義更新方法。因為ChainMap中有個屬性maps持有完整的各個映射,可以基于此屬性來完成相同鍵的一次性更新。這里簡單給個通過方法的方式實現(xiàn)多映射相同鍵的一次更新。示例代碼如下:
當(dāng)然,你可以寫得更復(fù)雜一點,以完成更多的需要,也可實現(xiàn)一次多個映射中的相同鍵的值。自己動手試試吧。
本文小結(jié)
本文主要介紹了Python集合模塊中的鏈?zhǔn)接成淙萜鳌狢hainMap的使用,可以把多個字典打包成一個對象來操作。同時需要注意的是,該映射只是對原字典的引用,當(dāng)你修改原字典時,相應(yīng)的變化也為體現(xiàn)在鏈?zhǔn)接成渲?。同時,在為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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.
