How to make a copy of chained dicts effectively and nicely?

Peter Otten __peter__ at web.de
Tue Sep 27 09:44:06 EDT 2016


Nagy László Zsolt wrote:

> The result that I need should be a real dict, not just a ChainMap. (It
> is because I have to mutate it.)
> 
> d1 = {'a':1, 'b':2}
> d2 = {'c':3, 'd':4}
> d3 = {'e':5, 'f':6}
> 
> #1. My first naive approach was:
> 
> 
> from collections import ChainMap
> d = {}
> for key,value in ChainMap(d1, d2, d3).items():
>     d[key] = value
> 
> #2. Much more effective version, but requires too many lines:
> 
> d= {}
> d.update(d1)
> d.update(d2)
> d.update(d3)

Unsolicited advice: you have to reverse the order with respect to ChainMap 
if there are duplicate keys:

>>> a = dict(a=1, b=2)
>>> b = dict(b=3, c=4)
>>> d = {}
>>> d.update(a)
>>> d.update(b)
>>> d == dict(ChainMap(a, b))
False
>>> d == dict(ChainMap(b, a))
True

With that in mind here's another version for your zoo:

>>> class MyChainMap(ChainMap):
...     def materialized(self):
...         d = {}
...         for map in reversed(self.maps):
...             d.update(map)
...         return d
... 
>>> MyChainMap(b, a).materialized()
{'a': 1, 'c': 4, 'b': 3}
>>> _ == d
True

If you say

> requires too many lines

is counter with "Write once, run anywhere".




More information about the Python-list mailing list