Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created July 9, 2020 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/4dc1cf4044ab12f2d769d3c3acaba85b to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/4dc1cf4044ab12f2d769d3c3acaba85b to your computer and use it in GitHub Desktop.
from collections import ChainMap
#two dictionaries having unique keys
d1={'a':1,'b':2}
d2={'c':3,'d':4}
d3=ChainMap(d1,d2)
print (d3)#Output:ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})
#two dictionaries having same key
d3={'a':1,'b':2}
d4={'a':3,'d':4}
d5=ChainMap(d3,d4)
print (d5)#Output:ChainMap({'a': 1, 'b': 2}, {'a': 3, 'd': 4})
#if we access the value of 'a', it will return the value of 'a" in first mapping(d3 in this example)
print (d5['a'])#Output:1
#same dictionary, we have given in different order.[(d4,d3) in this example]
d6=ChainMap(d4,d3)
print (d6)#Output:ChainMap({'a': 3, 'd': 4}, {'a': 1, 'b': 2})
#If we access value of 'a' now,it wil return the value of 'a' from first mapping (d4) in this exampple.
print (d6['a'])#Output:3
#If no maps are specified,single empty dictionary is provided.
d7=ChainMap()
print (d7)#Output:ChainMap({})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment