Home > Article > Backend Development > Python merge multiple dictionaries or mapping tutorial
Question
Now there are multiple dictionaries or mappings, and you want to logically merge them into a single Perform some operation after mapping, such as looking up a value or checking whether certain keys exist.
Solution
Join you have the following two dictionaries:
a = {'x': 1, 'z': 3 } b = {'y': 2, 'z': 4 }
Now assume that you must perform a search operation in two dictionaries (for example, first Search from a, if not found then search in b). A very simple solution is to use the ChainMap class from the collections module. For example:
from collections import ChainMap c = ChainMap(a,b) print(c['x']) # Outputs 1 (from a) print(c['y']) # Outputs 2 (from b) print(c['z']) # Outputs 3 (from a)
Discussion
A ChainMap accepts multiple dictionaries and logically turns them into one dictionary. However, these dictionaries are not really merged together. The ChainMap class just creates a list internally to hold these dictionaries and redefines some common dictionary operations to traverse this list. Most dictionary operations can be used normally, for example:
>>> len(c) 3 >>> list(c.keys()) ['x', 'y', 'z'] >>> list(c.values()) [1, 2, 3] >>>
If a duplicate key appears, the first occurrence of the mapped value will be returned. Therefore, c['z'] in the example program will always return the corresponding value in dictionary a, not the corresponding value in b.
Updating or deleting a dictionary always affects the first dictionary in the list. For example:
>>> c['z'] = 10 >>> c['w'] = 40 >>> del c['x'] >>> a {'w': 40, 'z': 10} >>> del c['y'] Traceback (most recent call last): ... KeyError: "Key not found in the first mapping: 'y'" >>>
ChainMap is very useful for scope variables in programming languages (such as globals, locals, etc.). In fact, there are some ways to make it easy:
>>> values = ChainMap() >>> values['x'] = 1 >>> # Add a new mapping >>> values = values.new_child() >>> values['x'] = 2 >>> # Add a new mapping >>> values = values.new_child() >>> values['x'] = 3 >>> values ChainMap({'x': 3}, {'x': 2}, {'x': 1}) >>> values['x'] 3 >>> # Discard last mapping >>> values = values.parents >>> values['x'] 2 >>> # Discard last mapping >>> values = values.parents >>> values['x'] 1 >>> values ChainMap({'x': 1}) >>>
As an alternative to ChainMap, you might consider using the update() method to merge the two dictionaries. For example:
>>> a = {'x': 1, 'z': 3 } >>> b = {'y': 2, 'z': 4 } >>> merged = dict(b) >>> merged.update(a) >>> merged['x'] 1 >>> merged['y'] 2 >>> merged['z'] 3 >>>
This would also work, but it would require you to create a completely different dictionary object (or destroy the existing dictionary structure). At the same time, if the original dictionary is updated, this change will not be reflected in the new merged dictionary. For example:
>>> a['x'] = 13 >>> merged['x'] 1
ChianMap uses the original dictionary and does not create a new dictionary itself. So it will not produce the results mentioned above, such as:
>>> a = {'x': 1, 'z': 3 } >>> b = {'y': 2, 'z': 4 } >>> merged = ChainMap(a, b) >>> merged['x'] 1 >>> a['x'] = 42 >>> merged['x'] # Notice change to merged dicts 42 >>>
Recommended tutorial: "Python Tutorial"
The above is the detailed content of Python merge multiple dictionaries or mapping tutorial. For more information, please follow other related articles on the PHP Chinese website!