Home  >  Article  >  Backend Development  >  Python method and analysis of merging multiple mappings into a single mapping (code example)

Python method and analysis of merging multiple mappings into a single mapping (code example)

不言
不言forward
2018-11-26 16:39:492112browse

The content of this article is about the method and analysis (code examples) of merging multiple mappings into a single mapping in Python. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. helped.

1. Requirements

We have multiple dictionaries or mappings and want to logically merge them into a single mapping structure to perform some Specific operations, such as looking up a value or checking if a key exists.

2. Solution

Suppose there are two dictionaries:

a={'x':1,'z':3}
b={'y':2,'z':4}

Now suppose we want to perform a search operation, we must check these two dictionaries ( For example, search in a first, and if not found, search in b). A simple way is to use the ChainMap class in the collections module to solve this problem. For example:

from collections import ChainMap
a={'x':1,'z':3}
b={'y':2,'z':4}
c=ChainMap(a,b)
print(c['x'])
print(c['y'])
print(c['z'])
print(len(c))
print(list(c.keys()))
print(list(c.values()))
a['z']=5
print(c['z'])

Running results:

1
2
3
3
['y', 'z', 'x']
[2, 3, 1]
5

3. Analysis

ChainMap can accept multiple mappings and logically behave as a single mapping mechanism. However, these mappings are not merged together at runtime. Instead, ChainMap simply maintains a list recording the underlying mapping relationships, and then redefines common dictionary operations to scan this list. Most list operations work fine. For example: len, keys(), values().

If there are duplicate keys, the corresponding value in the first mapping will be used.

The operation of modifying the mapping will always act on the first mapping structure listed. For example:

del c['x'] #可以正常删除a中的'x':1
del c['y'] #会移除,因为第一个映射结构a中没有y键

As an alternative to ChainMap, we may consider using the dictionary's update() method to merge multiple dictionaries together, for example:

from collections import ChainMap
a={'x':1,'z':3}
b={'y':2,'z':4}
#为了防止b被直接修改,先cope一份b
c=dict(b)
print(id(c))
print(id(b))
c.update(a)
print(c['x'])
print(c['y'])
print(c['z'])

Running result:

4550769400
4549694808
1
2
3

This works, but it requires building a complete dictionary object separately (or modifying one of them directly, which will destroy the original data). In addition, if any of the original dictionaries is modified, the changes will not be reflected in the merged dictionary, but ChainMap will.

The above is the detailed content of Python method and analysis of merging multiple mappings into a single mapping (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete