📜  Python中的链图

📅  最后修改于: 2022-05-13 01:54:27.758000             🧑  作者: Mango

Python中的链图

Python包含一个名为“ ChainMap ”的容器,它将许多字典封装到一个单元中。 ChainMap 是模块“集合”的成员。

例子:

# Python program to demonstrate  
# ChainMap  
       
       
from collections import ChainMap  
       
       
d1 = {'a': 1, 'b': 2} 
d2 = {'c': 3, 'd': 4} 
d3 = {'e': 5, 'f': 6} 
    
# Defining the chainmap  
c = ChainMap(d1, d2, d3)  
       
print(c)

输出:

ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})

我们来看看 ChainMap 上的各种操作

访问操作

  • 键(): -
  • 该函数用于显示 ChainMap 中所有字典的所有

  • values() :- 该函数用于显示ChainMap中所有字典的值。

  • maps() :- 该函数用于显示 ChainMap 中所有字典的键和对应值
# Please select Python 3 for running this code in IDE
# Python code to demonstrate ChainMap and
# keys(), values() and maps
  
# importing collections for ChainMap operations
import collections
  
# initializing dictionaries
dic1 = { 'a' : 1, 'b' : 2 }
dic2 = { 'b' : 3, 'c' : 4 }
  
# initializing ChainMap
chain = collections.ChainMap(dic1, dic2)
  
# printing chainMap using maps
print ("All the ChainMap contents are : ")
print (chain.maps)
  
# printing keys using keys()
print ("All keys of ChainMap are : ")
print (list(chain.keys()))
  
# printing keys using keys()
print ("All values of ChainMap are : ")
print (list(chain.values()))

输出 :

All the ChainMap contents are : 
[{'b': 2, 'a': 1}, {'c': 4, 'b': 3}]
All keys of ChainMap are : 
['a', 'c', 'b']
All values of ChainMap are : 
[1, 4, 2]

注意:请注意,两个字典中都存在名为“b”的键,但只有第一个字典键被视为“b”的键值。排序是在函数中传递字典时完成的。

操纵操作

  • new_child() :-
  • 此函数在 ChainMap 的开头添加一个新字典。

  • reversed() :- 此函数反转 ChainMap 中字典的相对顺序。
# Please select Python 3 for running this code in IDE
# Python code to demonstrate ChainMap and
# reversed() and new_child()
  
# importing collections for ChainMap operations
import collections
  
# initializing dictionaries
dic1 = { 'a' : 1, 'b' : 2 }
dic2 = { 'b' : 3, 'c' : 4 }
dic3 = { 'f' : 5 }
  
# initializing ChainMap
chain = collections.ChainMap(dic1, dic2)
  
# printing chainMap using map
print ("All the ChainMap contents are : ")
print (chain.maps)
  
# using new_child() to add new dictionary
chain1 = chain.new_child(dic3)
  
# printing chainMap using map
print ("Displaying new ChainMap : ")
print (chain1.maps)
  
# displaying value associated with b before reversing
print ("Value associated with b before reversing is : ",end="")
print (chain1['b'])
  
# reversing the ChainMap
chain1.maps = reversed(chain1.maps)
  
# displaying value associated with b after reversing
print ("Value associated with b after reversing is : ",end="")
print (chain1['b'])

输出 :

All the ChainMap contents are : 
[{'b': 2, 'a': 1}, {'b': 3, 'c': 4}]
Displaying new ChainMap : 
[{'f': 5}, {'b': 2, 'a': 1}, {'b': 3, 'c': 4}]
Value associated with b before reversing is : 2
Value associated with b after reversing is : 3