ChainMap simple example

ChainMap is a subclass of dict, dict has all the features, with its sense of place, right ???

 

from Collections Import ChainMap 

"" " 
     the equivalent of two join operation dict 

" "" 

# Example. 1 
dict1 = { " A " :. 1, " B " : 2 } 
dict2 = { " C " :. 3, " D " :. 4 } 

chain_dict = ChainMap (dict1, dict2)
 for K, V in chain_dict.items ():
     Print (K, V) 

'' ' 
Print results: 
C. 3 
D. 4 
A. 1 
B 2 
' ''

print(' - ' * 50 ) 

# Example 2 

dict1 = { " A " :. 1, " B " : 2 } 
dict2 = { " B " :. 3, " D " :. 4 } 

chain_dict = ChainMap (dict1, dict2)
 for K, V in chain_dict.items ():
     Print (K, V) 

'' ' 
Print results: b appears only once, the first time is the value of 
B 2 
D. 4 
a. 1 

' '' 
Print ( ' - ' * 50)
# 示例3
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

chain_dict = ChainMap(dict1, dict2)

chain_dict.update({'e': 8})


for k,v in chain_dict.items():
    print(k,v)

'''
c 3
d 4
a 1
b 2
e 8
'''

print('-' * 50 )
 # exemplary. 4 
dict1 = { " A " :. 1, " B " : 2 } 
dict2 = { " C " :. 3, " D " :. 4 } 

chain_dict = ChainMap (dict1, dict2) 

Print (chain_dict) 

# Remove and return an item pair from maps [0]. Raise KeyError is maps [0] is empty. ' feeling futile 
Item = chain_dict.popitem ()
 Print (Item)   # (' B ', 2) 

# POP only can pop chain_map element [0], chicken bit 
value = chain_dict.pop('a')
print(value)  #1
print(chain_dict)    # ChainMap({}, {'c': 3, 'd': 4})


print('-' * 50)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

chain_dict = ChainMap(dict1, dict2)

# new_chain_dict = chain_dict.new_child()
#print (new_chain_dict) # ChainMap ({ }, { 'a': 1, 'b': 2}, { 'c': 3, 'd': 4}), which die dim 

# add a new chain_map the dict 
new_chain_dict = chain_dict.new_child ({ ' name ' : ' ADMIN ' })
 Print (new_chain_dict)   # ChainMap ({ 'name': 'ADMIN'}, { 'a':. 1, 'B': 2}, { 'c': 3, 'd ': 4})

Guess you like

Origin www.cnblogs.com/z-qinfeng/p/12038753.html