Skip to content

Instantly share code, notes, and snippets.

@andela-anandaa
Last active April 11, 2017 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save andela-anandaa/cff61f241d919d93ac349431a3d45c08 to your computer and use it in GitHub Desktop.
Save andela-anandaa/cff61f241d919d93ac349431a3d45c08 to your computer and use it in GitHub Desktop.
Going through Python 3's ChainMap
from collections import ChainMap
# Traditionally, you can combine dictionaries into one,
# however, this creates a totally new dictionary
# e.g. for Python 3.5, you could do this:
a = {'name': 'Andela'}
b = {'class': 'World'}
c = {**a, **b}
# Notice, if a or b are updated, (obviously) c does not change
# And c, will be using extra memory the size of a + b
# With ChainMap
d = ChainMap(a, b)
print d # ChainMap({'name': 'Andela'}, {'class': 'World'})
print d['name'] # 'Andela'
# However, note that ChainMap only creates an interface through which
# the specific values of the dictionaries can be accessed.
# There's a catch though. If we have duplicate keys with different values,
# Only the first one will be picked, e.g.
d = ChainMap(a, b, {'name': 'NG'})
print d # 'Andela'
d = ChainMap({'name': 'NG'}, a, b}
print d # 'NG'
# Conclusion: the beauty of ChainMap is in the ability to create
# a handy interface through which you can access multiple dictionaries
# at once; with minimal extra memory usage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment