DEV Community

Discussion on: How to Merge Two Dictionaries in Python

Collapse
 
matt profile image
Matt seymour • Edited

Do not forget about ChainMap, ChainMap is really memory efficient way of working with multiple dictionaries as single data structure. It is extremely powerful.

From the Python documentation:

A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.
The underlying mappings are stored in a list. That list is public and can be accessed or updated using the maps attribute. There is no other state.
Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.
A ChainMap incorporates the underlying mappings by reference. So, if one of the underlying mappings gets updated, those changes will be reflected in ChainMap.
All of the usual dictionary methods are supported. In addition, there is a maps attribute, a method for creating new subcontexts, and a property for accessing all but the first mapping:


  • In a lot of your examples the dictionaries will be duplicated (or you will have duplication of key-values), this is fine for smaller dataset but when you start working with large dictionaries you might start chewing through a lot more memory than you would like.

  • In your examples you are also dealing with a small set of dictionaries (2-3). Where chainmap is useful is if you have many (10' or 100's or 1000's) of dictionaries.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

It always amazes me just how big the standard library is. For instance, I’ve never heard of ChainMap. Thanks for the tip.

Also, good considerations! To be fair, I was only considering two dictionaries based on the title, and I usually don’t worry too much about premature optimization. If these solutions ended up being a bottleneck, I might look into ChainMap.