본문 바로가기
Python

[Python] ChainMap in collections

by llHoYall 2021. 5. 2.

ChainMap class is provided for quickly linking a number of mappings so they can be treated as a single unit.

from collections import ChainMap  
         
dict1 = {'a': 1, 'b': 2} 
dict2 = {'b': 3, 'c': 4} 
    
cm = ChainMap(dict1, dict2)
print(cm)
# ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})

print(list(cm.keys()))
# ['b', 'c', 'a']

print(list(cm.values()))
# [2, 4, 1]

print(list(cm.items()))
# [('b', 2), ('c', 4), ('a', 1)]

Attributes

maps

The list is ordered from first-searched to last-searched.

print(cm.maps)
# [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}]

parents

Property returning a new ChainMap containing all of the maps in the current instance except the first one.

dict1 = {'a': 1, 'b': 2} 
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5, 'e': 6}
    
cm = ChainMap(dict1, dict2)
print(cm.parents)
# ChainMap({'b': 3, 'c': 4})

cm2 = ChainMap(dict1, dict2, dict3)
print(cm2.parents)
# ChainMap({'b': 3, 'c': 4}, {'d': 5, 'e': 6})

Methods

new_child(m=None)

Returns a new ChainMap containing a new map followed by all of the maps in the current instance.

If m is specified, it becomes the new map at the front of the list of mappings.

This method is used for creating subcontexts that can be updated without altering values in any of the parent mappings.

dict1 = {'a': 1, 'b': 2} 
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5, 'e': 6}
    
cm = ChainMap(dict1, dict2)
print(cm.new_child())
# ChainMap({}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})

print(cm.new_child(dict3))
# ChainMap({'d': 5, 'e': 6}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})

'Python' 카테고리의 다른 글

[Python] itertools module  (0) 2021.05.15
[Python] functools module  (0) 2021.05.08
[Python] namedtuple in collections  (0) 2021.05.02
[Python] Counter in collections  (0) 2021.05.01
[Python] OrderedDict in collections  (0) 2021.05.01

댓글