
PYTHON — MappingProxyType in Python’s ChainMap
The best way to predict the future is to invent it. — Alan Kay

PYTHON — Python- Working with Unix Time
ChainMap and MappingProxyType are two classes in Python’s collections and types libraries that are used to manipulate and manage dictionaries.
The purpose of ChainMap is to group multiple dictionaries into a single mapping, providing the ability to search for a key across all the dictionaries inside the map. For example, to create a ChainMap with two dictionaries, ships and space_ships, we can use the following code:
import collections
ships = {'Beagle': 'Darwin', 'Endeavour': 'Cook'}
space_ships = {'Apollo': 'NASA', 'Enterprise': 'Star Trek'}
chain = collections.ChainMap(ships, space_ships)To access elements from the ChainMap, we can use the standard dictionary syntax:
print(chain['Beagle']) # Output: Darwin
print(chain['Enterprise']) # Output: Star TrekIn this example, since the key “Enterprise” exists in both dictionaries, the response to the “Enterprise” key is for the aircraft carrier rather than for the space shuttle, as ChainMap responds with the first key in the order of the dictionaries that it can find.
Any changes made to the ChainMap will impact the dictionaries associated with it. For example, adding a new key to the ChainMap will modify the first dictionary associated with the ChainMap, which may not be the expected behavior. Therefore, it is recommended to use ChainMap mainly for reading keys from multiple dictionaries, and to perform insertions or deletions directly on the dictionaries themselves.
In contrast, MappingProxyType from the types library in Python 3.3 provides a read-only wrapper to a dictionary. This allows for creating a dictionary that cannot be altered after creation. For example:
import types
writable = {'one': 1, 'two': 2, 'three': 3}
read_only = types.MappingProxyType(writable)
print(read_only['one']) # Output: 1
# Attempting to change the key will raise an error
read_only['two'] = 20 # Raises: TypeError: 'mappingproxy' object does not support item assignmentAs seen in the example, attempting to modify the read-only dictionary will result in a TypeError. However, changes made to the original dictionary will reflect in the read-only mapping.
In summary, ChainMap is useful for grouping and reading keys from multiple dictionaries, while MappingProxyType provides a way to create a read-only wrapper around a dictionary. When choosing between these data structures, it is important to consider the specific requirements of the application.







