ChainMap Python Example

The python collections.ChainMap class can combine multiple python dictionary objects into one dictionary object, this article will tell you how to use it with some examples.

1. Python collections.ChainMap Object Characters.

  1. The python ChainMap object does not merge multiple python dictionary objects, it just links the multiple python dictionary objects into one.
  2. The dictionary object at the front when creating the ChainMap object has high priority. For example, you construct a ChainMap object with the code cm = ChainMap(dict1, dict2), and both dict1 and dict2 contains a key ‘score‘, and when you call cm[‘score’], it will return the value in dict1 because it is added to the ChainMap object first.

2. Python collections.ChainMap Examples.

2.1 Python ChainMap Example 1.

  1. This is a basic usage of ChainMap class, you can see the code comments for a detailed explanation.
    # first import collections.ChainMap class.
    from collections import ChainMap
    
    
    def chain_map_basic():
        
        # define 3 python dictionaries, the first and the second python dict contains the same key python.
        coding_lang_score = {'python':100, 'java':99, 'c':95}
        
        coding_lang_score_1 = {'python':90, 'javascript':98, 'c++':96}
        
        coding_ide_score = {'pydev':90,'eclipse':80, 'notepad':80}
        
        # combine the above 3 python dictionary objects to create a ChainMap object.
        cm = ChainMap(coding_lang_score, coding_lang_score_1, coding_ide_score)
        
        # Print the ChainMap object.
        print(cm)
        
        # Print each dictionary element in the ChainMap.
        print('python score : ' + str(cm['python']))
        
        print('javascript score : ' + str(cm['javascript']))
        
        print('pydev score : ' + str(cm['pydev']))
        
        
        
    
    if __name__ == '__main__':
        
        chain_map_basic()
  2. Below is the above example output.
    ChainMap({'python': 100, 'java': 99, 'c': 95}, {'python': 90, 'javascript': 98, 'c++': 96}, {'pydev': 90, 'eclipse': 80, 'notepad': 80})
    python score : 100
    javascript score : 98
    pydev score : 90
    

2.2 Python ChainMap Example 2.

  1. The below example will link python local, global and built-in variables into a ChainMap object, then when you get the variable value through the ChainMap object, it will search the variable in python local, global, and built-in order, then return the variable value accordingly.
    # first import collections.ChainMap class.
    from collections import ChainMap
    
    import builtins
    
    # define 2 global variables. 
    coding_lang = 'java'  
    
    coding_ide = 'pydev'  
        
    def chain_map_variable_scope():
       
        # define a local variable. 
        coding_lang = 'python'
        
        variable_search = ChainMap(locals(), globals(), vars(builtins))
        
        print('local variable - coding language : ' + variable_search['coding_lang'])
        
        print('global variable - coding ide : ' + variable_search['coding_ide'])
        
        # print the python built-in function.
        print(variable_search['len'])
        
    
    if __name__ == '__main__':
        
        chain_map_variable_scope()
  2. Below is the above example output.
    local variable - coding language : python
    global variable - coding ide : pydev
    <built-in function len>
    

2.3 Python ChainMap Example 3.

  1. The following example demonstrates the implementation of first using the specified parameters of the running python script, then use the system environment variables, and finally using the defaults varialbe values. The example also links these three search ranges into a ChainMap object.
    # first import collections.ChainMap class.
    from collections import ChainMap
    
    import os, argparse
    
      
    def chain_map_varible_param_env_defaut():
        
        # define a dictionary variable contains color and user key.
        defaults = {'color':'blue', 'user':'jerry'}
        
        # Parse user input python program parameters.
        parser = argparse.ArgumentParser()
        parser.add_argument('-u', '--user')  
        parser.add_argument('-c', '--color')  
        
        namespace = parser.parse_args()
        
        # Convert the command line parameters to a python dictionary object. 
        cmd_args_dict = {}
        
        for k, v in vars(namespace).items():
            
            if v :
                cmd_args_dict[k] = v 
        
        '''
         Link this python script command line parameters, os system environment variables and a local variable to create a ChainMap object.
         From the below parameters order we can see the cmd_args_dict has the highest priority, so if user specify -c or -u parameter when run this script in command line,
         the cmd_cm['color'] or cmd_cm['user'] will return the command line parameter value than the defaults variable value.
        '''
        cmd_cm = ChainMap(cmd_args_dict, os.environ, defaults)  
        print(cmd_cm)
        
        # print the value in the ChainMap object by key. The below 2 variable value will come from  either command line arguments or the defaults variable.
        print(cmd_cm['color'])  
        print(cmd_cm['user'])
        
        # The below variable should come from the os environment variables.
        print(cmd_cm['PYTHONPATH'])
    
    if __name__ == '__main__':
        
        chain_map_varible_param_env_defaut()
  2. Below is the above example output when you run the python script with the command python ChainMapExample.py -c Green in a console .
    ChainMap({'color': 'Green'}, environ({'PYDEV_COMPLETER_PYTHO......: 'UTF-8'}), {'color': 'blue', 'user': 'jerry'})
    # String green is from the script running parameters -c's value.
    Green
    
    # String jerry is from the local dictionary variable defautls's 'user' key, because when run this python script it does not provide the command parameter -u parameter value.
    jerry
    
    # Below is the value of system environment variable PYTHONPATH.
    /Use......n_example/lib/python3.7/site-packages
    
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x